场景:
如果对某变量进行赋值,是否需要判断一下,如果相等就不用赋值,这样会不会提高性能。
代码如下:
string a = "";
string b = ""; long x1=, x2=, x3=; Stopwatch w = new Stopwatch(); for (int x = ; x < ; x++)
{
w.Reset();
w.Start();
for (int i = ; i < ; i++)
{
a = b;
}
w.Stop();
x1 += w.ElapsedMilliseconds; w.Reset();
w.Start();
for (int i = ; i < ; i++)
{
if(a != b)
a = b;
}
w.Stop();
x2 += w.ElapsedMilliseconds; w.Start();
for (int i = ; i < ; i++)
{
if (!a.Equals(b))
a = b;
}
w.Stop();
x3 += w.ElapsedMilliseconds;
} System.Diagnostics.Debug.WriteLine(String.Format("直接赋值耗时:{0}ms", x1));
System.Diagnostics.Debug.WriteLine(String.Format("判断赋值耗时:{0}ms", x2));
System.Diagnostics.Debug.WriteLine(String.Format("判断赋值2耗时:{0}ms", x3));
运行结果:
直接赋值耗时:3294ms
判断赋值耗时:5955ms
判断赋值2耗时:18244ms
结论:
判断后严重影响性能,所以无需判断,直接赋值。