虚拟函数与函数指针-性能? [英] virtual function vs. function pointer - performance?

查看:58
本文介绍了虚拟函数与函数指针-性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在多态基类上调用C ++虚拟函数是否和调用C样式函数指针一样快?真的有什么区别吗?

我正在考虑重构一些使用功能指针的注重性能的代码,并将其转换为多态的虚拟函数.

解决方案

我会说大多数C ++实现的工作方式都与此类似(而且可能是第一个编译成C的实现产生的代码是这样的:

  struct ClassVTABLE {void(* virtuamethod1)(Class * this);void(* virtuamethod2)(Class * this,int arg);};结构类{ClassVTABLE * vtable;}; 

然后,在给定实例 Class x 的情况下,为其调用方法 virtualmethod1 就像 x.vtable-> virtualmethod1(& x),因此有一个额外的解除引用,从 vtable 中进行了一次索引查找,还有一个额外的参数(= this )被压入了堆栈/传入了寄存器.

但是,编译器可能可以优化函数中某个实例的重复方法调用:由于实例 Class x 在构造后无法更改其类,因此编译器可以考虑整个 x.vtable-> virtualmethod1 作为常见的子表达式,然后将其移出循环.因此,在这种情况下,在单个函数中重复进行虚拟方法调用的速度将等同于通过简单的函数指针调用函数的速度.

Are C++ virtual functions called on a polymorphic base class just as fast as calling a C-style function pointer? Is there really any difference?

I'm considering refactoring some performance-minded code that utilizes function pointers and change them over to virtual functions in polymorphism.

解决方案

I'd say most of the C++ implementations work similar to this (and probably the first implementations, that compiled into C, produced code like this):

struct ClassVTABLE {
    void (* virtuamethod1)(Class *this);
    void (* virtuamethod2)(Class *this, int arg);
};

struct Class {
    ClassVTABLE *vtable;
};

Then, given an instance Class x, calling the method virtualmethod1 for it is like x.vtable->virtualmethod1(&x), thus one extra dereference, 1 indexed lookup from the vtable, and one extra argument (= this) pushed onto the stack / passed in registers.

However the compiler probably can optimize repeated method calls on an instance within a function: since an instance Class x cannot change its class after it is constructed, the compiler can consider the whole x.vtable->virtualmethod1 as a common sub-expression, and move it out of loops. Thus in this case the repeated virtual method calls within a single function would be equivalent in speed to calling a function via a simple function pointer.

这篇关于虚拟函数与函数指针-性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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