Why is it recommended to check string length to determine emptiness?
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: 开发者_JS百科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.
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).
The reason is by doing s == ""
you are doing a string comparison which is slower than the other way (s.Length == 0
)
In most of my code, using string.IsNullOrEmpty()
or string.IsNullOrWhiteSpace()
(in .NET 4) are easier to read and more specifically do what I really need done.
s == string.Empty is an alternate to s.length == 0.
My guess on why s == "" is not recommended is that "" would create a immutable string on heap. Just for comparison, you may not want to create a string object. Anyhow someone may validate my statment.
String values comparision is slower than numeric values comparision.
I would use String.IsNullOrEmpty in your case.
not all dot net strings are interned at runtime that means that s.Length == 0 would be faster in those cases as it avoids an actual string comparison which results if one of two strings is not interned See String.IsInterned() on MSDN
精彩评论