Thursday, February 19, 2009

String Comparisions : Performance test to find out blank strings

We can compare blank strings as below.

str == ""
str == string.Empty
str.Equals("")
st.Equals(string.Empty)
str.Length==0

I did small performance testing to find out which gives us best performance and I found


3. str == "" and str == string.Empty almost same
2. str.Equals("") and st.Equals(string.Empty) almost same
1. str.Length==0 real difference (It takes the least time)

You can also test it using the below code:

string print = "";
string str = "test";
long startTicks = DateTime.Now.Ticks;

for (int i = 0; i < 40000000; i++)
{
if (str == "")
{
}

}
long endTicks = DateTime.Now.Ticks - startTicks;
print = "str == \"\" " + endTicks.ToString() + "\n";
startTicks = DateTime.Now.Ticks;
for (int i = 0; i < 40000000; i++)
{
if (str.Equals(""))
{
}

}
endTicks = DateTime.Now.Ticks - startTicks;
print += "str.Equals(\"\") " + endTicks.ToString() + "\n";
startTicks = DateTime.Now.Ticks;
for (int i = 0; i < 40000000; i++)
{
if (str == string.Empty)
{
}

}
endTicks = DateTime.Now.Ticks - startTicks;
print += "str == string.Empty " + endTicks.ToString() + "\n";
startTicks = DateTime.Now.Ticks;
for (int i = 0; i < 40000000; i++)
{
if (str.Equals(string.Empty))
{
}

}
endTicks = DateTime.Now.Ticks - startTicks;
print += "str.Equals(string.Empty) " + endTicks.ToString() + "\n";
startTicks = DateTime.Now.Ticks;
for (int i = 0; i < 40000000; i++)
{
if (str.Length==0)
{
}
}
endTicks = DateTime.Now.Ticks - startTicks;
print += "str.Length==0 " + endTicks.ToString() + "\n";
MessageBox.Show(print);

Happy Coding

No comments:

Site Meter