65.9K
CodeProject is changing. Read more.
Home

Testing for Empty String

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.02/5 (13 votes)

Feb 21, 2008

CPOL
viewsIcon

48296

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

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