This posting was born after reading a nice comparison in "Maximizing .NET Performance" by Nick Wienholt.
The book claims that comparing an empty string to "" or string.Empty is slower than comparing the Length to 0.
Testing this claim is one of the easiest things to do:
int j = 0;
int k = 0;
int l = 0;
string s = "";
Console.WriteLine(DateTime.Now);
for (int i = 0; i < int.MaxValue; i++)
{
if (s == "")
{
j++;
}
}
Console.WriteLine(DateTime.Now);
for (int i = 0; i < int.MaxValue; i++)
{
if (s == string.Empty)
{
k++;
}
}
Console.WriteLine(DateTime.Now);
for (int i = 0; i < int.MaxValue; i++)
{
if (s.Length == 0)
{
l++;
}
}
Console.WriteLine(DateTime.Now);
Console.ReadKey();
//Avoid the optimiser by "using" the action variables
Console.WriteLine(j);
Console.WriteLine(k);
Console.WriteLine(l);
The results are shocking at first:
1st run:
Compare to "": 32 sec
Compare to string.Empty: 51 sec
Compare the Length to 0: 26 sec
2nd run:
Compare to "": 28 sec
Compare to string.Empty: 48 sec
Compare the Length to 0: 7 sec
3rd run:
Compare to "": 28 sec
Compare to string.Empty: 48 sec
Compare the Length to 0: 7 sec
While the book claimed that comparing to "" or to string.Empty is the same, my computer "translated" the string.Empty to "" prior to the comparison. The result is a slower comparison.
The main conclusion from this experiment is:
TEST THE BLOODY THING ON YOUR PLATFORM! The book is usually tested on some platforms, but not on YOUR platform.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment