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?
I had someone advise me to avoid repeatedly calling String.Length , because it was
Share
That’s bad advice –
String.Lengthis indeed O(1). It’s not likestrlenin 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…