什么是标记方法/属性作为虚拟化的性能影响? [英] What are the performance implications of marking methods / properties as virtual?

查看:114
本文介绍了什么是标记方法/属性作为虚拟化的性能影响?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题作为标题指出:什么是标记方法/属性作为虚拟性能的影响

Question is as stated in the title: What are the performance implications of marking methods / properties as virtual?

请注意 - 我假设虚拟方法将的的在通常情况下超载;我通常会被这里的基类的工作。

Note - I'm assuming the virtual methods will not be overloaded in the common case; I'll usually be working with the base class here.

推荐答案

相比,直接调用虚函数只有一个非常小的性能开销。在一个较低的水平,你基本上看阵列查找来获得一个函数指针,然后通过一个函数指针调用。现代的CPU甚至可以predict间接函数调用合理地在其分支机构predictors,所以他们一般不会伤害现代CPU管道太差。在程序集级别,虚函数调用转换为类似于以下,其中 I 是一个任意的即时值。

Virtual functions only have a very small performance overhead compared to direct calls. At a low level, you're basically looking at an array lookup to get a function pointer, and then a call via a function pointer. Modern CPUs can even predict indirect function calls reasonably well in their branch predictors, so they generally won't hurt modern CPU pipelines too badly. At the assembly level, a virtual function call translates to something like the following, where I is an arbitrary immediate value.

MOV EAX, [EBP + I] ; Move pointer to class instance into register
MOV EBX, [EAX] ;  Move vtbl pointer into register.
CALL [EBX + I]  ;   Call function

Vs以上。一个直接的函数调用如下:

Vs. the following for a direct function call:

CALL I  ;  Call function directly

真正的开销来在这虚函数不能被内联,在大多数情况下。 (他们可以在JIT语言如果VM认识他们总是要相同的地址无论如何)。除此之外,您还从内联本身得到加速,内联使几个其他优化,如常量折叠,因为主叫方可以知道如何被调用者内部工作原理。对于那些有足够的不被内联无论如何大功能,性能损失将可能是微不足道的。对于可能被inline非常小的功能,那就是当你需要小心虚函数。

The real overhead comes in that virtual functions can't be inlined, for the most part. (They can be in JIT languages if the VM realizes they're always going to the same address anyhow.) Besides the speedup you get from inlining itself, inlining enables several other optimizations such as constant folding, because the caller can know how the callee works internally. For functions that are large enough not to be inlined anyhow, the performance hit will likely be negligible. For very small functions that might be inlined, that's when you need to be careful about virtual functions.

编辑:要记住的另一件事是,所有的程序都需要流量控制,这是从来没有免费的。什么会取代你的虚函数? switch语句?一系列的if语句?这些仍然是分支,可能是未predictable。此外,鉴于N路分支,一系列的if语句会发现在O(N)正确的路径,而虚函数将在O(1)找到它。 switch语句可能O(N)或O(1)根据是否经过优化,跳转表。

Another thing to keep in mind is that all programs require flow control, and this is never free. What would replace your virtual function? A switch statement? A series of if statements? These are still branches that may be unpredictable. Furthermore, given an N-way branch, a series of if statements will find the proper path in O(N), while a virtual function will find it in O(1). The switch statement may be O(N) or O(1) depending on whether it is optimized to a jump table.

这篇关于什么是标记方法/属性作为虚拟化的性能影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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