如果,开关和函数指针速度比较 [英] if, switch and function pointers speed comparison

查看:145
本文介绍了如果,开关和函数指针速度比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个小解释器,所以我想测试ifs,开关和指针到函数的速度,彼此相比。如果使用19 else ifs比稍微快于20个case的切换,并且函数指针(20个函数指针的数组)比前两个慢...

I'm building a small interpreter so I wanted to test how fast ifs, switch and pointers to functions are, compared to each other. if with 19 else ifs is slightly faster than switch with 20 cases, and function pointers (an array of 20 function pointers) is way slower than the previous two...

我希望结果完全相反,任何人都可以解释一下。

I expected the results to be completely opposite, can anyone please explain?

推荐答案

在现代处理器上,到分支预测。虽然switch语句可以实现为跳转表,它需要大约相同的时间来执行代码的任何分支,但它通常是相当不可预测的 - 字面上;分支预测器通常在预测哪个分支被采用上做得相当差,这意味着管道气泡(通常大约15个浪费的循环等)的机会很大。

On a modern processor, a lot of this comes down to branch prediction. While a switch statement can be implemented as a jump table that takes about the same length of time to execute any branch of the code, it's also generally pretty unpredictable -- literally; a branch predictor will often do a fairly poor job of predicting which branch gets taken, which means there's a very good chance of a pipeline bubble (typically around 15 wasted cycles or so).

if语句可以做更多的比较,但大多数分支几乎每次都采用相同的方式,所以分支预测器可以更准确地预测他们的结果。

An if-statement may do more comparisons, but most of the branches are probably taken the same way nearly every time, so the branch predictor can predict their results much more accurately.

函数的指针也是相当不可预测的。更糟的是,直到最近,大多数处理器甚至没有尝试。只是最近才对大多数BTB(分支目标缓冲区)实现添加足够的,他们甚至可以真正尝试通过指针来预测分支的目标。在较老的处理器上,指向函数的指针在速度比较上通常做得相当差。

Pointers to functions can also be fairly unpredictable. Worse, until fairly recently, most processors pretty much didn't even try. Only fairly recently did the add enough to most BTB (Branch Target Buffer) implementations that they can really even make a serious attempt at predicting the target of a branch via a pointer. On older processors, pointers to functions often do quite poorly in speed comparisons.

这篇关于如果,开关和函数指针速度比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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