简体   繁体   English

使用虚函数而不是IF语句更快?

[英]Using virtual functions instead of IF statements is faster?

I remember reading online somewhere that in EXTREMELY low latency situations its better to use virtual functions as a substitute for IF statements. 我记得在某处在线阅读,在极端低延迟的情况下,最好使用虚函数代替IF语句。

Is this true? 这是真的? Are they basically saying dynamic polymorphism is better for speed situations? 他们基本上说动态多态性对于速度情况更好吗?

Do any users have any other C++ low latency "quirks" they could share? 是否有任何用户可以分享任何其他C ++低延迟“怪癖”?

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. 我非常怀疑单个if / else语句比使用虚函数要慢:虚函数通常会强制执行管道停顿并限制优化机会。 An if statement may stall the pipeline but if it is often executed the prediction may go the right way. if语句可能会使管道停止,但如果经常执行,则预测可能会以正确的方式进行。 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. 但是,如果您的替代方案是在几个if / else语句的级联与仅一个虚函数调用之间,则后者可能更快。 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, ie 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 eg for message processing it is often sufficient to have one dynamic decision eg one for each message (ie one virtual function call), followed by processing which doesn't involve any dynamic types (this are still conditionals, eg for the amount of values in a table). 在我用过这个例如消息处理的区域中,通常有一个动态决策就足够了,例如每个消息一个(即一个虚函数调用),然后是不涉及任何动态类型的处理(这仍然是条件,例如,对于表中的值的数量)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM