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

I want to check if a string string data contains an empty string.

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

I forgot to say that data was checked and guaranteed not to be null .

+4
source share
9 answers

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 

a source

+13
source

Use String.IsNullOrEmpty(data) rather

+11
source

I will choose the third one, it will be less error prone:

String.IsNullOrEmpty(data)

+2
source

I would say that you should use the String.isNullOrEmpty method to check for zeros.

+2
source

No check will be your bottleneck. However, if you choose the first option, you can NullReferenceException if the string is null. You would not have this problem with the second.

+2
source

Logically, data.Length == 0 more efficient because it just compares two integer values, while data == String.Empty compares strings (albeit very short).

However, there are a number of optimizations that a potential compiler or framework can minimize or eliminate any difference. This makes it difficult to make absolute statements without having to run your own time tests.

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

+2
source

Best practice is to use String.IsNullOrEmpty (or, if it meets 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 that you will need to check if(s == null || s.Length == 0) . This will be the most efficient and probably the fastest, but you can use String.IsNullOrEmpty .

s == string.Empty will return false if the string is null ( null does not match the empty string).

As far as performance is concerned, do not spare more time thinking about it. It will almost never, never, never, never, ever affect performance.

+2
source

As already mentioned, use string.IsNullOrEmpty(str) or string.IsNullOrWhiteSpace(str) embedded in .NET 4.0.

+2
source

Use String.IsNullOrEmpty() to check.

+1
source

All Articles