使用虚函数而不是 IF 语句更快? [英] Using virtual functions instead of IF statements is faster?

查看:24
本文介绍了使用虚函数而不是 IF 语句更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我记得在某处在线阅读,在极低延迟的情况下,最好使用虚拟函数代替 IF 语句.

I remember reading online somewhere that in EXTREMELY low latency situations its better to use virtual functions as a substitute for IF statements.

这是真的吗?他们基本上是说动态多态性更适合速度情况吗?

Is this true? Are they basically saying dynamic polymorphism is better for speed situations?

是否有任何用户可以分享其他任何 C++ 低延迟怪癖"?

Do any users have any other C++ low latency "quirks" they could share?

推荐答案

我非常怀疑单个 if/else 语句会比使用虚函数慢:虚函数通常会强制执行管道停顿并限制优化机会.if 语句可能会使管道停止运行,但如果经常执行,则预测可能会以正确的方式进行.但是,如果您的替代方案是在几个 if/else 语句的级联与仅一个虚函数调用之间,那么后者可能会更快.此外,如果通过使用虚拟函数与分支执行的总代码是不同的函数,最终会显着更小,则可能会导致指令缓存上的缓存未命中很少.也就是说,视情况而定.最好的方法是测量.请注意,测量只是试图研究两种方法之间的差异但并未真正进行任何处理的人工代码会产生误导性结果.但是,当您需要生成非常低延迟的代码时,您通常可以花更多时间来想出它,即尝试多种不同的方法可能是可行的.

I very much doubt that a single if/else statement would be slower than using a virtual function: the virtual function typically enforces a pipeline stall and limits the optimization opportunities. An if statement may stall the pipeline but if it is often executed the prediction may go the right way. However, if your alternative is between a cascade of a few if/else statements vs. just one virtual function call than that latter may be faster. Also, if the total code being executed via using virtual functions vs. branches is different functions ends up substantially smaller it may cause few cache misses on the instruction cache. That is, it depends on the situation. The best way is to measure. Note that measuring artificial code which is just attempting to investigate the difference between two approaches but doesn't really do any processing yields misleading results. However, when you need to produce very low latency code you typically can spend more time to come up with it, i.e. experimenting with multiple different approaches may be viable.

尽管我的同事倾向于不赞成我避免运行时分支的模板方法,但我最终得到的代码通常编译起来很慢,但运行起来却很快.当然,这取决于编译时已知的函数或分支.在我使用过的领域,例如对于消息处理,通常有一个动态决策就足够了,例如每个消息一个(即一个虚函数调用),然后是不涉及任何动态类型的处理(这仍然是条件,例如对于表中的值的数量).

Although my colleagues tend to frown upon my template approaches for avoiding run-time branching, the code I end up with often is very slow to compile but very fast to run. Of course, this depends on the functions or branches being used to be known at compile time. In the areas I have used this e.g. for message processing it is often sufficient to have one dynamic decision e.g. one for each message (i.e. one virtual function call), followed by processing which doesn't involve any dynamic types (this are still conditionals, e.g. for the amount of values in a table).

这篇关于使用虚函数而不是 IF 语句更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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