111,126
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace TestNullStrCmp
{
class Program
{
//private String strBase = new String("a");
static void Main(string[] args)
{
//定义
string strBase = "abc"+"";
Random rd = new Random();
List<string> ls = new List<string>();
string str="";
//strng str=Sring.Empty;
int k = 0;
int k1 = 0, k2 = 0, k3 = 0, k4 = 0;
//构造一个列表,里面有很多字符串和空字符串
for (int j = 1; j < 1000000; j++)
{
k++;
for (int i = 0; i < 4; i++)
{
StringBuilder sb = new StringBuilder();
sb.Append(strBase[rd.Next(0, strBase.Length)]);
}
if (k % 2 == 0)
ls.Add(str);
else
ls.Add("");
}
//使用四种方法进行判断
//方法一
Stopwatch timer1 = new Stopwatch();
timer1.Start();
foreach (var item in ls)
{
if (0 == item.Length)
k1=0;
}
timer1.Stop();
Console.WriteLine("对于0 == item.Length");
Console.WriteLine(timer1.Elapsed.Milliseconds + "ms");
Console.WriteLine();
//Console.WriteLine("k1: {0}", k1);
//方法二
Stopwatch timer2 = new Stopwatch();
timer2.Start();
foreach (var item in ls)
{
if ("" == item)
k2=0;
}
timer2.Stop();
Console.WriteLine("对于\"\" == item");
Console.WriteLine(timer2.Elapsed.Milliseconds + "ms");
Console.WriteLine();
//Console.WriteLine("k2: {0}",k2);
//方法三
Stopwatch timer3 = new Stopwatch();
timer3.Start();
foreach (var item in ls)
{
if (String.Empty == item)
k3=0;
}
timer3.Stop();
Console.WriteLine("对于String.Empty == item");
Console.WriteLine(timer3.Elapsed.Milliseconds + "ms");
Console.WriteLine();
//Console.WriteLine("k3: {0}", k3);
/*
//方法四
Stopwatch timer4 = new Stopwatch();
timer4.Start();
foreach (var item in ls)
{
if (String.IsNullOrEmpty(item))
k4=0;
}
timer4.Stop();
Console.WriteLine("对于String.IsNullOrEmpty(item)");
Console.WriteLine(timer4.Elapsed.Milliseconds + "ms");
Console.WriteLine();
//Console.WriteLine("k4: {0}", k4);
*/
Console.ReadKey();
}
}
}