函数实际上比函数指针快吗? [英] Are functors actually faster than pointers to functions?

查看:119
本文介绍了函数实际上比函数指针快吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据斯科特·迈耶斯(Scott Meyers)的观点,C ++超越C的一个方面是函数对象比函数指针要快.他说这是因为内联了函数对象,从而提高了速度.

According to Scott Meyers, one area where C++ shines over C is that function objects are faster than function pointers. He says this is because function objects are inlined, which increases speed.

对此我有两个问题:

  1. 我们如何验证实际上是内联的函数对象?我们可以在实践中验证吗?

  1. How can we verify that function objects are, in fact, inlined? Can we verify this in practice?

函数对象的内联是否取决于我们使用的编译器,还是所有编译器的行为都如此?

Does the inlining of function objects depend on the compiler we use, or do all compilers behave like this?

推荐答案

C ++和C标准为编译器留出了很多自由.编译器可以自由地在每条指令之间计数到10亿,或者只有在整数中有素数时才这样做.

The C++ and C standards leaves a bunch of freedom to compilers. Compilers are free to count to 1 billion between every instruction, or only do so if an integer has a prime value in it.

体面的真实"编译器不会这样做.这是实施质量问题.

Decent "real" compilers don't do this. This is a quality of implementation issue.

每个真正的编译器都会将函数对象内联到类似std::sort的位置.在这种情况下,检测需要内联的内容非常容易,因为类型信息会附带需要内联的代码.

Inlining function objects into something like std::sort is something that every real compiler does. It is exceedingly easy to detect what needs to be inlined in those cases, because the type information carries with it the code needed to be inlined.

使用函数指针执行此操作比较困难.使用将所有内容都转换为void*char*指针的函数指针执行此操作更加困难.

Doing so with a function pointer is harder. Doing so with a function pointer where everything has been converted to void* or char* pointers is even harder.

这样做的效果是,实际上,对qsort的C样式调用与对std::sort的C ++样式调用可以为std::sort带来很大的优势.

The effect of this is that, in practice, a C-style call to qsort vs a C++-style call to std::sort can result in an large advantage for std::sort.

qsort大约比std::sort慢2倍,如此处,在对随机排列的整数进行排序的荒谬简单情况下.

qsort is roughly 2x slower than std::sort, as shown here, in a ridiculously simple situation of sorting randomly arranged integers.

检查实际的汇编代码输出主要是一个细节,这是很多工作,很少有回报.以具体的实际示例为例,您可以了解影响的真正程度.

Inspecting the actual assembly code output is mainly a detail, and it is a lot of work for little return. Taking concrete real-world examples gives you an idea of how big the impact really is.

clang,gcc和MSVC中的所有3种能够使std::sort的速度明显快于其qsort的速度.并且由于这是一个简单的优化,而将函数指针优化为内联调用却并非如此,因此您希望较少的主要编译器在qsort上不会比这更好.

All 3 of clang, gcc and MSVC where able to make std::sort be significantly faster than their qsort. And as this is an easy optimization, while optimizing function pointers into inline calls is not, you'd expect less major compilers to be no better than this at qsort.

这篇关于函数实际上比函数指针快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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