1、判断空字符串大概有如下方法
1、 stirng.IsNullOrEmpty()
2、 和 String.IsEmpty 比较
3、 和 "" 比较
4、 用String.Equal("")比较,字符串变量不能为null,否则报异常,效率次至
5、 用String.Length == 0 判断,字符串变量不能为null,否则报异常, 效率最高
static void Main(string[] args)
{
Stopwatch timeWatch = new Stopwatch();
string strTest = string.Empty;
///方法一 string.length 判断,字符串不能为null
timeWatch.Start();
for (int index = 0; index < 10000000; index++)
{
if (strTest.Length == 0)
{
}
}
timeWatch.Stop();
Console.WriteLine(timeWatch.Elapsed + ":string.length耗时");
///方法二 string.Equals("") 判断 ,字符串不能为null
timeWatch.Start();
for (int index = 0; index < 10000000; index++)
{
if (strTest.Equals(""))
{
}
}
timeWatch.Stop();
Console.WriteLine(timeWatch.Elapsed + ":string.Equals()耗时");
///方法三 string.Empty 判断, 字符串可以为null
timeWatch.Start();
for (int index = 0; index < 10000000; index++)
{
if (strTest== string.Empty)
{
}
}
timeWatch.Stop();
Console.WriteLine(timeWatch.Elapsed + ":string.Empty耗时");
///方法四 "" 判断
timeWatch.Start();
for (int index = 0; index < 10000000; index++)
{
if (strTest == "")
{
}
}
timeWatch.Stop();
Console.WriteLine(timeWatch.Elapsed + ":\"\"比较耗时");
///方法五 string.IsNullOrEmpty 判断
timeWatch.Start();
for (int index = 0; index < 10000000; index++)
{
if (string.IsNullOrEmpty(strTest))
{
}
}
timeWatch.Stop();
Console.WriteLine(timeWatch.Elapsed + ":string.IsNullOrEmpty耗时");
/*说明:== 运算符和Equal() 函数功能是一样的,二者都是对值进行了比较 .net类库string类的源码如下
public static bool operator == (String a, String b) {
return String.Equals(a, b);
}*/
Console.ReadKey();
}