本文介绍了downcasting的性能如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试着通过阅读

释义..当您定义一个Generic类定义时,它将被编译为IL。

Paraphrasing.. When you define a Generic class definition, it is compiled into IL.


  • 对于值类型,只要您请求特定的值类型,它就会将T替换为您的特定值类型以获取该特定配置的IL MyList< int> 好处:无装箱和取消装箱处罚。 ,编译器用Object替换定义中T的所有实例,并创建用于所有ref类型的IL。然而,实例是基于实际请求的参考类型分配的,例如, MyList< String>

  • For value-types, as soon as you request for a specific value-type, it substitutes the T with your specific value type to obtain the IL for that specific configuration e.g. MyList<int> Benefit: No boxing and unboxing penalties.
  • All good.. for reference types, the compiler replaces all instances of T in your definition with Object and creates the IL which is used for all ref types. Instances however are allocated based on the actual requested ref type e.g. MyList<String>

现在我们可以编写方法取 Object 参数。泛型要求100%的性能提升,因为它避免了当你想要使用它时将对象类型向下转换为特定类型时性能的损失。

Now pre-generics we could have written methods that take Object parameters. Generics claims 100% performance improvement because 'it avoids the performance penalty you incur when you downcast the object type to your specific type when you want to use it'

 // assume GetItem returns an Object
 string sMyPreciousString = (string) obList.GetItem(); 

当您从对象向下转换为特定引用类型时,此性能如何影响?此外,它似乎是向上对象转换(即使泛型会做到这一点)是不是一个性能打击..为什么?

What is this performance hit when you downcast from Object to specific reference type? Also it seems like up-casting to Object (even Generics would do this) isn't a performance hit.. why?

推荐答案

上传到对象并不需要执行时间检查 - 它会一直工作,基本上只是一个无操作。

Upcasting to object doesn't require an execution time check - it will always work, and is just a no-op basically.

向下转换需要执行时间检查才能使例如,确定你没有将一个流投射到一个字符串。这是一个非常小的罚款,并且不太可能成为瓶颈 - 但避免它只是泛型的一个额外好处。

Downcasting requires an execution time check to make sure you're not casting a Stream to a String for example. It's a pretty small penalty, and very unlikely to be a bottleneck - but avoiding it is just one extra benefit for generics.

这篇关于downcasting的性能如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 15:29