投射一个对象有多昂贵? [英] How Expensive is Casting an Object?
问题描述
可能的重复:
TypeCasting 的性能
将一个对象转换为另一个对象的代价有多大?
CustomClass instance = GenericObject as CustomClass
是否应该避免所有成本?
想看看其他人是怎么想的.我确定这是非常特殊的情况.
您应该避免担心特定语言功能对性能的影响,除非您有具体的证据(测量)表明它们确实导致了问题.
em>
您主要关心的应该是代码的正确性和可维护性.
然而,作为一般观察,在 C# 中通常可以避免不必要的强制转换,只需应用良好的 OO 编程实践并适当地使用泛型(尤其是集合).在您确实需要执行转换的情况下,除非您在紧密循环中执行转换或使用可能引发无效转换异常的类型,否则它不太可能成为性能瓶颈.
大多数现实世界的性能问题都源于算法选择或缺乏对平台本身的认识,而不是特定的语言特性.
Possible Duplicate:
Perfomance of TypeCasting
How expensive is it to cast as object as a another object?
CustomClass instance = GenericObject as CustomClass
Should it be avoided as all costs?
Wanting to see how others think about this. I'm sure it's very situational.
You should avoid worrying about the performance implications of specific language features unless you have specific evidence (measurements) that they are actually causing a problem.
Your primary concerns should be the correctness of the code and it's maintainability.
As a general observation, however, unnecessary casting can often be avoided in C# just by applying good OO programming practices and using generics (particularly the collections) appropriately. In those cases where you do need to perform casting, it's highly unlikely to be a performance bottleneck unless you're doing it in a tight loop or with types that are likely to throw an invalid cast exception.
Most real world performance problems emerge from algorithm choices or a lack of awareness of the platform itself - not from specific language features.
这篇关于投射一个对象有多昂贵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!