Display Name
Display Name

Reputation: 15081

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.

Which 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.

Upvotes: 4

Views: 3098

Answers (9)

Peter
Peter

Reputation: 27944

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

Upvotes: 13

devdigital
devdigital

Reputation: 34349

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

Upvotes: 2

David Neale
David Neale

Reputation: 17018

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.

Upvotes: 2

Jonathan Wood
Jonathan Wood

Reputation: 67195

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.

Upvotes: 2

Anthony Pegram
Anthony Pegram

Reputation: 126804

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.

Upvotes: 2

Magnus Johansson
Magnus Johansson

Reputation: 28325

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

Upvotes: 2

oleksii
oleksii

Reputation: 35895

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

String.IsNullOrEmpty(data)

Upvotes: 2

VMAtm
VMAtm

Reputation: 28345

Use String.IsNullOrEmpty() to check.

Upvotes: 1

Rahul
Rahul

Reputation: 77866

Use String.IsNullOrEmpty(data) rather

Upvotes: 11

Related Questions