在 C# 中,哪一个更快? Convert.ToString()、(string)casting 还是 .ToString()?
在 C# 中,哪个更快?
- System.Convert.ToString(objThatIsAString)
- (字符串)objThatIsAString
- objThatIsAString.ToString()
In C#, which one is faster?
- System.Convert.ToString(objThatIsAString)
- (string)objThatIsAString
- objThatIsAString.ToString()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
@蒂斯:
这是一个快速测试:
结果:
转换 100000 个字符串后平均经过的刻度数
ConvertToString:611.97372 刻度数
ToString:586.51461 刻度数
CastToString:582.25266 刻度数
@thijs:
Here's a quick test:
Results in:
Average elapsed ticks after converting 100000 strings
ConvertToString: 611.97372 ticks
ToString: 586.51461 ticks
CastToString: 582.25266 ticks
除了运行时类型检查之外,直接转换不需要进行任何检查 - 我期望转换速度更快。
您可能还想考虑 objThatIsString.ToString() ; 因为(对于
string
)这只是return this;
,它应该很快 - 当然比Convert.ToString
更快。 然后,竞争就发生在运行时类型检查和虚拟调用之间; 事实上,两者都非常非常快。The direct cast doesn't have to do any checking except a runtime type check - I would expect that the cast is quicker.
You might also want to consider
objThatIsString.ToString()
; since (forstring
) this is justreturn this;
, it should be quick - certainly quicker than theConvert.ToString
. Then the race is between a runtime type-check and a virtual call; in reality, both are very, very quick.演员阵容更快。
Convert.ToString
最终将在一些开销后进行转换。 它实际上是通过尝试将其转换为 IConvertible,然后调用其虚拟方法 ToString 的形式来实现的。 因此,实际上是虚拟调用将其转换为String
。The cast is faster.
The
Convert.ToString
will eventually do a cast after some overhead. It actually does it in the form of attempting to cast it toIConvertible
, and then call the virtual methodToString
on it. So, it's the virtual call that does the actual casting toString
.转换
(string)obj
应该更快。 Convert 类实际上转换不同类的对象,在这种情况下会比较慢。The cast
(string)obj
should be faster. The Convert class actually converts objects that are of different class and will be slower in this case.有句话说“数字说明故事”。 这意味着您不仅可以假设某些东西,还可以测量它!
因此,打包一个测试应用程序,运行测试并验证结果!
真正的问题可能是:
如何衡量哪种方式更快?
There's a saying "The numbers tell the tale". Which means that instead of assuming something you can also measure it!
So, wrap up a test app, run your tests and validate the results!
The true question could be:
How do I measure which way is faster?
我认为
(string) objThatIsString
更快,因为编译器将能够在编译时进行此转换。然而,Jeff Atwood 认为这毕竟不重要 (编码恐怖:微的悲伤悲剧-优化剧场)
I think that
(string) objThatIsString
is faster because the Compiler will be able to do this conversion at compile time.However, Jeff Atwood thinks that its not important after all (Coding Horror: The Sad Tragedy of Micro-Optimization Theater)