Jonas Stawski

Everything .NET and More

String.Empty, null, Length, or String.IsEmptyOrNull ?

Every time i have to deal with strings (almost every time) I stop and wonder which way is really the fastest way to check for an empty string. Of course the string.Length == 0 check should be the fastest since Length is a property and there shouldn't be any processing other than retrieving the value of the property. But then I ask myself, why is there a String.Empty? It should be faster to check for String.Empty than for length, I tell myself. Well i finnaly decided to test it out. I coded a small Windows Console app that tells me how long it takes to do a certain check for 10 million repitions. I checked 3 different strings: a NULL string, an Empty string, and a "" string. I used 5 different methods: String.IsNullOrEmpty(), str == null, str == null || str == String.Empty, str == null || str == "", str == null || str.length == 0. Below are the results:

String.IsNullOrEmpty()
--------------------------------
NULL = 62 milliseconds
Empty = 46 milliseconds
"" = 46 milliseconds

str == null
---------------
NULL = 31 milliseconds
Empty = 46 milliseconds
"" = 31 milliseconds

str == null || str == String.Empty
----------------------------------------------
NULL = 46 milliseconds
Empty = 62 milliseconds
"" = 359 milliseconds

str == null || str == ""
------------------------------
NULL = 46 milliseconds
Empty = 343 milliseconds
"" = 78 milliseconds

str == null || str.length == 0
---------------------------------------
NULL = 31 milliseconds
Empty = 63 milliseconds
"" = 62 milliseconds

According to these results, on average checking for str == null is the fastest, but might not always yield what we're looking for. if str = String.Empty or str = "", it results in false. Then you have 2 that are tied in second place: String.IsNullOrEmpty() and str == null || str.length == 0. Since String.IsNullOrEmpty() looks nicer and is easier (and faster) to write I would recommend using it over the other solution. Of course String.IsNullOrEmpty is only for .NET 2.0 so if you're using .net 1.X then the second solution should be good for you.

Happy Programming!

Comments (5) -

Life sucks, or its just ones stupid idea?

Reply

This was helpful, thanks

Reply

The akkadian
The akkadian

Thanks!
that was very helpful!

Reply

Jonas Stawski,

Very crafty. This comments serve to me.

Reply

Only an idiot would care.

Reply

Add comment

biuquote
Loading