Performance Tips: Test For Empty Strings Using String Length in C#

By | June 4, 2014

Test for empty strings using string length, not string.Empty or “” to get the best performance.

Because of the implementation of the string class, the most performant method for testing for an empty string is to test for the string length equal to zero. Other methods are effective, but are less performant.

Possible Violations of Rule:

Test for empty string with string.Length instead of string.Empty

Test for empty string with string.Length instead of “” All rule violations are can be automatically corrected with devAdvantage.

Examples of testing for empty string [C#]

public string bar(string foo )

{ string test;

if(foo == string.Empty ) //Very slow

test = “Very slow”; if ( foo == “” ) //Slow

test = “Slow”;

if(foo != null && foo.Length == 0 ) //Most performant way to test for empty string

else if ( foo test = “Fast”; return test; }

Leave a Reply