C# String Perf Take # 2 ( Accused : IsNullOrEmpty() )

String is a reference type. The IsNullOrEmpty is used to check weather string reference is null (null) or contains any data (empty string). According to MSDN :

“Comparing strings using the String.Length property or the String.IsNullOrEmpty method is significantly faster than using Equals. This is because Equals executes significantly more MSIL instructions than either IsNullOrEmpty or the number of instructions executed to retrieve the Length property value and compare it to zero.”

// 733 ms : Checks string for null, and then checks against ""

if (s == null || s == "")

// 546 ms : Calls string.IsNullOrEmpty static method in framework

if (string.IsNullOrEmpty(s))

// 406 ms : Checks string for null, and then check Length

if (s == null || s.Length == 0)

Also like I’ve mentioned in one of my posts, if s.Length == 0 gets replaced by s.Length.Equals(0)


Published by

Aarsh Talati

Software Developer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s