David Connell

Software Developer - Red Gate Software

Testing for empty String

Published Friday, November 18, 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] == ‘\0’ 25
 
Test Native C++/MFC & TCHAR
strVal[0] == ‘\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.

    Comments

    No Comments
    You need to sign in to comment on this blog

















    <November 2005>
    SuMoTuWeThFrSa
    303112345
    6789101112
    13141516171819
    20212223242526
    27282930123
    45678910
    Go With the Flow
     Knowing enough about the routes that messages take is vital to being an effective Exchange admin,... Read more...

    When Email Collaboration Could Have Changed History
     In our mission to make history relevant to the busy IT executive, we speculate how Email might have... Read more...

    Bunnikins!
     When an IT manager is selected as a victim of office politics of a large corporate, it is time for him... Read more...

    Exchange Database Technologies
     One of the most misunderstood technologies in Exchange Server, regardless of its version, is the... Read more...

    Top Tips for Exchange Admins
     Michael Francis hands out imaginary Olympic medals to the winner of the August 'Top Tips for Exchange... Read more...