Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it recommended to check string length to determine emptiness?

Tags:

c#

Often, people say that it is better to say s.Length == 0 instead of s == "". But it seems like this would be a microoptimization that also makes it harder to read. Also, ten million of the former as opposed to the latter save at best 60 ms.

Is there a reason that I'm missing, such as if perhaps s.Length == 0 actually conveys the intent better? Or is it common to need to compare many strings for emptiness?

EDIT: I know about IsNullOrEmpty, but when people answer the question, they often mention that length checking is better than comparing to the empty string.

EDIT2: Not asking about the best way to do this which would be IsNullOrEmpty for both cases, but I'm asking why it is that a non-negligible minority insist that length checking is superior. I'm assuming that they have some good reasons for saying so, and want to know what they are.

EDIT3: As stated in the beginning, I do know that one is faster than the other. The question is, is that the reason people recommend it? Some timings showed that this did not lead to significant differences.

like image 772
Jamie Avatar asked Dec 28 '22 18:12

Jamie


2 Answers

You're right, it's essentially a micro-optimisation. Testing the length does keep FxCop / Code Analysis quiet though - and the justification is performance, as documented in MSDN.

As for which is more readable, that's subjective, and I'm sure any developer would understand either. Since they are semantically different (s.Length == 0 throws if s is null, whereas s == "" doesn't), readability isn't the only criterion to consider.

In cases where you're not certain the string is not null, String.IsNullOrEmpty or String.IsNullOrWhiteSpace might be even more readable (i.e. expressive of your intention).

like image 84
Joe Avatar answered Dec 30 '22 07:12

Joe


The reason is by doing s == "" you are doing a string comparison which is slower than the other way (s.Length == 0)

like image 36
Naftali Avatar answered Dec 30 '22 07:12

Naftali