开发者

Which is more efficient, "data.Length==0" or "data==string.Empty"?

I want to check whether or not a variable string data contain empty string.

W开发者_Go百科hich is more efficient, data.Length==0 or data==string.Empty?

I forgot to say, the data has been checked and it is guaranteed to be not null.


Test results for 100 million iterations:

Equality operator ==:   796 ms 
string.Equals:          811 ms 
string.IsNullOrEmpty:   312 ms 
Length:                 140 ms  [fastest]
Instance Equals:       1077 ms 

source


Use String.IsNullOrEmpty(data) rather


I will choose the third one, it is less bug prone:

String.IsNullOrEmpty(data)


I would say that you should use the String.isNullOrEmpty method to check for nulls as well.


Neither check will be your bottleneck. However, if you opt for the first, you could run into a NullReferenceException if the string is null. You would not have that problem with the second.


Logically, data.Length == 0 is more efficient because it is simply comparing two integer values, whereas data == String.Empty is comparing strings (although very short ones).

However, there are a number of optimizations that the compiler or framework can potential make to minimize or eliminate any difference. This makes it hard to make absolute statements without running your own timing tests.

In the end, I doubt the difference will be enough to notice.


Best practice is to use String.IsNullOrEmpty (or, if it fits your requirements, from .Net 4.0 - String.IsNullOrWhiteSpace).

If you call s.Length then you will get a NullReferenceException if the string is null. This means you would need to check if(s == null || s.Length == 0). This will be the most effective and probably the quickest, but you might aswell use String.IsNullOrEmpty.

s == string.Empty would return false if the string was null (null is not the same as an empty string).

In terms of performance, don't spare any more time thinking about it. It will nearly never, never, never, never impact on performance.


As people have mentioned, use string.IsNullOrEmpty(str), or string.IsNullOrWhiteSpace(str) introduced in the .NET 4.0 framework.


Use String.IsNullOrEmpty() to check.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜