Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / .NET

Testing for Empty String

3.03/5 (13 votes)
21 Feb 2008CPOL 2  
A brief comparison of techniques of testing for empty strings

Background

Every once in a while, someone will post a snippet with code such as...

C#
if ( somestring == "" )

... and in many cases someone else will respond, "Always use if ( somestring.Length == 0 ), it's more efficient."

... or maybe someone will respond, "Always use if ( somestring == System.String.Empty ), it's more efficient."

And neither will back up his claim.

Here are some numbers; performing each test against a provided string (UInt32.MaxValue times) yields:

C:\>StrTest ""
00:01:09.3764731 // if ( providedstring == "" )
00:01:10.3869118 // if ( providedstring == localstaticemptystring )
00:01:10.1249723 // if ( providedstring == System.String.Empty )
00:00:38.1334581 // if ( providedstring.Length == 0 )

C:\>StrTest "abc"
00:01:36.3041617 // if ( providedstring == "" )
00:01:36.6285272 // if ( providedstring == localstaticemptystring )
00:01:35.9541459 // if ( providedstring == System.String.Empty )
00:00:31.6860051 // if ( providedstring.Length == 0 )

The difference between comparing against a literal empty string and a static empty string is negligible. And note that somehow when the provided string isn't empty, those tests take even longer!

Testing the Length of the string is the clear winner here, though it's not as Earth-shattering as some might have you believe.

History

  • 2008-02-21 First submitted

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)