xx.ToString() 和 (string)xx 哪个更快?

xx.ToString()将对象表示成字符串形式,前提是xx不能为null。

(string)xx将System.String对象、 其父类对象或其子类对象转换为string,xx可以为null。

哪个方法更快呢?

object aa = "this is a string.";

DateTime begin 
= DateTime.Now;
for (int i = 0; i < 1000000000; i++) {
     
string a = aa.ToString();
}

DateTime end 
= DateTime.Now;
TimeSpan timespan 
= end - begin; 

大约需要6.6-6.8秒

object aa = "this is a string.";

DateTime begin 
= DateTime.Now;
for (int i = 0; i < 1000000000; i++) {
      
string a = (string)aa;
}

DateTime end 
= DateTime.Now;
TimeSpan timespan 
= end - begin;

大约需要6.2秒。

 可能是因为xx.ToString()方法是虚方法调用,在解析方法表指针的时候花费了一些时间。

 

原文地址:https://www.cnblogs.com/ChenZB/p/1738314.html