于是我在想,为什么不直接进行赋值来进行变换,而通过替换局部字符串来变换呢?两者之间有什么区别?到底哪一种的性能会好点?于是带着种种疑问,设计了如下实验:
复制代码
using System;
using System.Diagnostics;
namespace test
{
class Program
{
static void Main(string[] args)
{
var str1 = “转到编辑界面”;
var num = 0;
while (num < 5)
{
test1(str1);
test2(str1);
num += 1;
System.Console.WriteLine("=====================");
}
}
private static void test1(string str1)
{
var num = 0; var str = str1;
var sw = new Stopwatch();
sw.Start();
while (num < 100000)
{
if (str == str1)
str = str.Replace("编辑", "预览");
else
str = str.Replace("预览", "编辑");
num += 1;
}
sw.Stop();
System.Console.WriteLine(sw.ElapsedMilliseconds);
}
private static void test2(string str1)
{
var num = 0; var str = "";
var sw = new Stopwatch();
sw.Start();
while (num < 100000)
{
str = str == str1 ? "转到预览界面" : "转到编辑界面";
num += 1;
}
sw.Stop();
System.Console.WriteLine(sw.ElapsedMilliseconds);
}
}
}
亚马逊测评www.yisuping.com