三种常用的字符串判空串方法执行速度比较
三种常用的字符串判空串方法:
1: bool isEmpty = (str.Length == 0);
2: bool isEmpty = (str == String.Empty);
3: bool isEmpty = (str == "");
哪种方法最快?
以下是测试代码:
using System;
public class strLengthTime
{
public static void Main()
{
string strTest = "";
string strSub;
for (int i = 0; i < 1000; i++)
{
strSub = i.ToString();
strTest = strTest + strSub;
}
DateTime startTime;
DateTime endTime;
TimeSpan timeCost;
startTime = DateTime.Now;
for (int m = 0; m < 100000000; m++)
{
if (strTest.Length == 0)
{
}
}
endTime = DateTime.Now;
timeCost = endTime - startTime;
System.Console.WriteLine("strTest.Length Method Costs:" + timeCost.TotalMilliseconds.ToString());
startTime = DateTime.Now;
for (int m = 0; m < 100000000; m++)
{
if (strTest == string.Empty)
{
}
}
endTime = DateTime.Now;
timeCost = endTime - startTime;
System.Console.WriteLine("String.Empty Method Costs:" + timeCost.TotalMilliseconds.ToString());
startTime = DateTime.Now;
for (int m = 0; m < 100000000; m++)
{
if (strTest == "")
{
}
}
endTime = DateTime.Now;
timeCost = endTime - startTime;
System.Console.WriteLine("The Third Method Costs:" + timeCost.TotalMilliseconds.ToString());
Console.ReadLine();
}
}
执行结果:
于是在今后的比较空串的时候,请多用 string.Length==0。