对于object的ToString()的调用,平时没有怎么注意,认为可有可无。实际上这个里面对性能有很大的影响,具体怎么样,看下面的例子就可以很清楚的知道了。
object obj1 = \"test\";
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < 1000000; i++)
...{
string t = Convert.ToString(obj1);
}
watch.Stop();
Console.WriteLine(\"1000000 times object: \" + watch.ElapsedMilliseconds + \"ms\");
object obj2 = \"test\";
Stopwatch watch1 = new Stopwatch();
watch1.Start();
for (int i = 0; i < 1000000; i++)
...{
string t = Convert.ToString(obj2.ToString());
}
watch1.Stop();
Console.WriteLine(\"1000000 times string: \" + watch1.ElapsedMilliseconds + \"ms\");
Console.ReadLine();
运行结果如下:
1000000 times object: 37ms
1000000 times string: 11ms