用这个方法,首先要保证对象不能为null,另外,本身是string类型的就没必要用这样的方法,多余不是关键,关键是效率低下。
执行下面的代码,你可以有所收货。
string str = "abcdefghigklmn";
string other = null;
Stopwatch sw = Stopwatch.StartNew();
sw.Start();
for (int i = 0; i < int.MaxValue; i++)
{
other = str.ToString();
}
sw.Stop();
Console.WriteLine("用了ToString()执行的时间:" + sw.ElapsedMilliseconds);
sw = null;
GC.Collect();
sw = Stopwatch.StartNew();
sw.Start();
for (int i = 0; i < int.MaxValue; i++)
{
other = str;
}
sw.Stop();
Console.WriteLine("不用ToString()执行的时间:" + sw.ElapsedMilliseconds);
Console.ReadLine();