Why is it recommended to determine the length of the string to determine the void?

Often people say it's better to say s.Length == 0 instead of s == "" . But it looks like it will be microoptimization, which also makes reading difficult. In addition, ten million of the former, unlike the latter, retain 60 ms at best.

Is there a reason why I am absent, for example, if perhaps s.Length == 0 really conveys the intention better? Or is it often necessary to compare many lines for emptiness?

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

EDIT2: Don’t ask how best to do this, what will be IsNullOrEmpty for both cases, but I ask why this small minority insists that checking the length is superior. I assume that they have good reason to talk about it, and they want to know what they are.

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

+4
source share
6 answers

You are right, this is, in fact, micro-optimization. Length testing really saves FxCop / Code Analysis, and - an excuse - performance, is documented in MSDN .

As for what is more readable, this is subjective, and I'm sure that any developer will understand too. Since they are semantically different ( s.Length == 0 throws if s is null and s == "" does not), readability is not the only criterion to consider.

In cases where you are not sure if the string is not null, String.IsNullOrEmpty or String.IsNullOrWhiteSpace can be even more readable (i.e. express your intentions).

+7
source

The reason is that you do s == "" , you are comparing strings, which is slower than in another ( s.Length == 0 )

+2
source

In most of my codes, using string.IsNullOrEmpty() or string.IsNullOrWhiteSpace() (in .NET 4), it is easier to read and more specifically do what I really need to do.

+1
source

s == string.Empty is an alternative to s.length == 0.

My guess about why s == "is not recommended is that" "will create an immutable string on the heap. For comparison, you can not create a string object. Somehow, someone can confirm my expression.

0
source

Comparing string values ​​is less than comparing numerical values.

I would use String.IsNullOrEmpty in your case.

0
source

not all dotted network strings are interned at run time, which means that s.Length == 0 will be faster in these cases because it avoids the actual string comparison that occurs if one of the two strings is not interned . See String.IsInterned () on MSDN

0
source

All Articles