Click here to monitor SSC

Software Developer - Red Gate Software

Testing for empty String

Published 18 November 2005 1:14 pm
I was speaking with James a few days ago about strings and testing for them being empty, and as usual we had an interesting discussion. At the end of it I thought I better go off and write some test code to find out some real numbers. I investigated three environments. .NET 1.1 .NET 2.0 and MFC7.1.
I took a rather simplistic model to profile, in order to make the tests more repeatable and easy to follow.

The .NET code followed the followed the structure:
[STAThread] static void Main(string[] args) 
{ 
    DateTime time = DateTime.Now; 
    string stringVal = “”; 
    for (int nIndex = 0; nIndex < 1000000000; nIndex++) 
    { 
        if (stringVal == string.Empty) 
        { 
        } 
    } 
    double TimeTaken = (DateTime.Now-time).TotalMilliseconds; 
    Console.WriteLine(string.Format(“Taken {0}”, TimeTaken)); 
} 

Yes that’s right the loop is 1 billion.
The results were as follows rounded to the nearest second. (Nb. An empty loop took around 0.5 second). The C++ code was very similar bar using things like CString etc….

Test .NET 1.1 .NET 2.0
stringVal.Length == 0 7 4
stringVal == “” 11 11
stringVal == String.Empty 11 17
string.IsNullOrEmpty(stringVal) 13.5* 9
 
Test Native C++/MFC & CString
stringVal.IsEmpty() 17
string.GetLength==0 13
stringVal[0] == ‘’ 25
 
Test Native C++/MFC & TCHAR
strVal[0] == ‘’ 2

(Nb. (*) For the .NET 1.1 IsNullOrEmpty test, I wrote a small class to simulate this function)
The machine that carried out the tests was an Intel 3.4Ghz P4 running XP SP2 with 1GB RAM.


This showed me a few things
  • NET performs exceedingly well in comparison to native code
  • Writing easy to read and maintainable code is better than trying to write optimum performing code
  • I would use IsNullOrEmpty(stringVal) because it is the most readable and explicit.

  • For additional information check out www.gotdotnet.com.

    Leave a Reply