为什么反射慢? [英] Why is reflection slow?

查看:28
本文介绍了为什么反射慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是不是因为我们应该加载类(例如通过string),创建实例,然后搜索合适的方法,打包参数,然后只是调用方法?所以大部分时间都花在了这些操作上,而不是对对象的显式方法调用上,对吧?

Is it because we should load class (by string for example), create instance, then search for appropriate method, pack parameters, and then just invoke method? So most time is spent on these operations instead of explicit method invocation on an object, right?

推荐答案

当你使用反射时,你采取的每一步都需要经过验证.例如,当您调用一个方法时,它需要检查目标是否实际上是该方法的声明者的实例,您是否获得了正确数量的参数,每个参数是否属于正确的类型等.

Every step you take needs to be validated every time you take it when you use reflection. For example, when you invoke a method, it needs to check whether the target is actually an instance of the declarer of the method, whether you've got the right number of arguments, whether each argument is of the right type, etc.

绝对不可能进行内联或其他性能技巧.

There's absolutely no possibility of inlining or other performance tricks.

如果您按名称查找类型或方法,那充其量只涉及一个简单的地图查找 - 每次执行时都会执行该查找,而不是在 JIT 时执行一次.

If you're finding types or methods by name, that's at best going to involve a simple map lookup - which will be performed every time you execute it, rather than once at JIT time.

基本上还有很多事情要做.然而,反射变得比以前快了很多……如果你发现它太慢了,你很可能过度使用它.

Basically there's a lot more to do. However, reflection has become a lot faster than it used to be... if you're finding it much too slow, you may well be overusing it.

这篇关于为什么反射慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆