开发者

What order of time does the .NET System.String.Length property take?

I had someone advise me to avoid repeatedly calling String.Length, because it was recalculated each time I called it. I had assumed that Str开发者_开发百科ing.Length ran in O(1) time. Is String.Length more complex than that?


That's bad advice - String.Length is indeed O(1). It's not like strlen in C.

Admittedly it's not guaranteed in the docs as far as I can tell, but the immutability of strings makes it a pretty silly thing not to make O(1). (And not just O(1), but a very fast constant time too.)

Frankly if someone is giving that sort of advice, I would become a bit more skeptical about other advice they may provide too...


String.Length is O(1). The reason people tell you not to call it in a loop is because it's a property access, which is the same as a method call. In reality one extra method call rarely makes any significant difference.

As always, don't start going through your code caching all calls to String.Length unless your profiler says it's the source of a performance problem.


Recall that strings are immutable. System.String.Length never changes.


No it does not recalculate. String type is immutable.

To take this further, as per the .net framework design guidelines, a property of an object that is very much static and non-volatile in nature would be designed as property. Should the property be of a volatile nature that needs recalculation on every call, it shall be made available as method.

you can take this rule while you attempt to check if a property takes enough processing cycles to attract your attention.


As others have said String.Length is a constant property. If you really care about performance (or have significant iterations), you could assign its value to a local integer variable once, and read that many times (in a loop, etc.). This would give the optimizer a better chance of allocating this value to a CPU register. Accessing a property is a much more expensive operation than a stack variable or a register.


According to the internal comments, the String.Length property is a single instruction that does not run a for loop. Therefore, it is an O(1) operation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜