vftable性能惩罚与switch语句 [英] vftable performance penalty vs. switch statement

查看:172
本文介绍了vftable性能惩罚与switch语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++问题在这里。我有一个系统,我要有一个给定的超类的数百个小子类。他们都将有一个foo方法做某事。或者...我将有一个类有一个整数称为类型,并使用一个巨大的switch语句来决定当我foo做什么。

C++ question here. I have a system where I'm going to have hundreds of mini-subclasses of a given superclass. They all will have a "foo" method that does something. Or... I'm going to have one class with an integer called "type" and use a giant switch statement to decide what to do when I foo.

性能是一个巨大的考虑。非常重要。

Performance is a huge consideration here. Extremely important.

问题是,使用switch语句的性能优点/惩罚是什么,让C ++通过vftable做到这一点?如果我有一个switch语句,我可以把常见的foo在switch语句的顶部,而不常见的底部,希望可以缩短比较。试图获得这样的效果与vftable一定是编译器依赖,即使我能弄清楚如何做... ...

The question is, what are the performance benefits/penalties of using a switch statement vs. letting C++ do it via the vftable? If I have it as a switch statement, I can put the commonly occuring foo's up at the top of the switch statement and the less common ones at the bottom, hopefully shortcutting the comparison. Trying to get an effect like this with the vftable is bound to be compiler dependent even if I can figure out how to do it...

另一方面,我的

推荐答案


如果我有这个丑陋的switch语句,它作为一个switch语句,我可以把常见的foo放在switch语句的顶部,而不太常见的底部,希望可以缩短比较。

If I have it as a switch statement, I can put the commonly occuring foo's up at the top of the switch statement and the less common ones at the bottom, hopefully shortcutting the comparison.

A switch 语句通常编译为跳转表,而不是你的问题暗示的 if-else 条件的块。在实践中,虚拟表和 switch 跳转表应该有类似的性能,虽然测试你是否真的关注。

A switch statement is generally compiled to a jump table rather than a block of if-else conditionals as your question implies. In practice, the virtual table and the switch jump table should have similar performance, though test if you're really concerned.

这篇关于vftable性能惩罚与switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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