Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 String.Length ran in O(1) time. Is String.Length more complex than that?

like image 704
Matthew Avatar asked May 14 '10 17:05

Matthew


5 Answers

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...

like image 101
Jon Skeet Avatar answered Oct 13 '22 00:10

Jon Skeet


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.

like image 40
Matti Virkkunen Avatar answered Oct 12 '22 23:10

Matti Virkkunen


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

like image 26
John Saunders Avatar answered Oct 12 '22 23:10

John Saunders


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.

like image 42
this. __curious_geek Avatar answered Oct 12 '22 23:10

this. __curious_geek


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.

like image 32
Simon Chadwick Avatar answered Oct 13 '22 01:10

Simon Chadwick