关于虚拟功能的成本 [英] about the cost of virtual function

查看:231
本文介绍了关于虚拟功能的成本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在一个循环中调用一个虚函数1000次,我将遭受vtable查找开销1000次还是只有一次?

If I call a virtual function 1000 times in a loop, will I suffer from the vtable lookup overhead 1000 times or only once?

推荐答案

Visual C ++编译器(至少通过VS 2008)不缓存vtable查找。更有趣的是,它不会将调用直接调度到虚拟方法,其中对象的静态类型是密封。然而,虚拟分派查找的实际开销几乎总是可忽略的。你有时候看到命中的地方是,C ++中的虚拟调用不能被直接调用替代,就像在受管理的VM中一样。这也意味着没有内联的虚拟调用。

The Visual C++ compiler (at least through VS 2008) does not cache vtable lookups. Even more interestingly, it doesn't direct-dispatch calls to virtual methods where the static type of the object is sealed. However, the actual overhead of the virtual dispatch lookup is almost always negligible. The place where you sometimes do see a hit is in the fact that virtual calls in C++ cannot be replaced by direct calls like they can in a managed VM. This also means no inlining for virtual calls.

唯一真正的方式来确定对您的应用程序的影响是使用分析器。

The only true way to establish the impact for your application is using a profiler.

关于你的原始问题的细节:如果你调用的虚拟方法是微不足道的,虚拟调度本身导致可衡量的性能影响,那么该方法是足够小,以使vtable将保留在处理器的缓存整个循环。即使从vtable中拉出函数指针的汇编指令执行了1000次,性能影响将远远小于(从系统内存加载vtable的时间为1000 *)

Regarding the specifics of your original question: if the virtual method you are calling is trivial enough that the virtual dispatch itself is incurring a measurable performance impact, then that method is sufficiently small that the vtable will remain in the processor's cache throughout the loop. Even though the assembly instructions to pull the function pointer from the vtable are executed 1000 times, the performance impact will be much less than (1000 * time to load vtable from system memory).

这篇关于关于虚拟功能的成本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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