2010年3月15日 星期一

Best Way to Check Empty String in C#

from http://dotnetperls.com/empty-string

Equality operator ==: 796 ms
string.Equals: 811 ms
string.IsNullOrEmpty: 312 ms
Length: 140 ms [fastest]
Instance Equals: 1077 ms
Using empty string methods

Here we see the five empty string tests shown in the graph and in the table above. Each of the five tests will be true, as the string str is empty. The code prints out the results of the tests, which you can see at the end.
=== Program that uses empty strings (C#) ===

class Program
{
static void Main()
{
// Example string
string str = "";

// Example tests
if (str == "")
{
// 1
// Test with op_Equality
System.Console.WriteLine(1);
}
if (string.Equals(str, ""))
{
// 2
// Test with static Equals method
System.Console.WriteLine(2);
}
if (string.IsNullOrEmpty(str))
{
// 3
// Test with IsNullOrEmpty
System.Console.WriteLine(3);
}
if (str.Length == 0)
{
// 4
// Test with Length property
System.Console.WriteLine(4);
}
if (str.Equals(""))
{
// 5
// Test with Equals method
System.Console.WriteLine(5);
}
}
}

沒有留言:

關於我自己

Aspire freedom , Hope to do Soming make self complete ~