C ++函数指针vs开关 [英] C++ Function pointers vs Switch

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

问题描述


  • 更快:函数指针或切换?

code> case s,由从0到30的枚举无符号整数组成。

The switch statement would have around 30 cases, consisting of enumarated unsigned ints from 0 to 30.

我可以执行以下操作:

class myType
{
    FunctionEnum func;
    string argv[123];
    int someOtherValue;
};
// In another file:
myType current;
// Iterate through a vector containing lots of myTypes
 // ... for ( i=0; i < myVecSize; i ++ )
    switch ( current.func )
    {
           case 1:
            //...
            break;
           // ........
           case 30:
             // blah
            break;
    }

然后通过 func 每次。关于switch的好处也是我的代码比30个函数更有条理。

And go trough the switch with func every time. The good thing about switch would also be that my code is more organized than with 30 functions.

或者我可以这样做(不太确定):

Or I could do that (not so sure with that):

class myType
{
    myReturnType (*func)(int all, int of, int my, int args );
    string argv[123];
    int someOtherValue;
};

我有30个不同的函数,在开头,指向其中一个的指针被分配给

I'd have 30 different functions then, at the beginning a pointer to one of them is assigned to myType.


  • 可能更快:切换语句或函数指针?

每秒呼叫数:约1000万。
我不能只是测试它 - 这将要求我重写整个事情。目前正在使用开关。

Calls per second: Around 10 million. I can't just test it out - that would require me to rewrite the whole thing. Currently using switch.

我正在构建一个解释器,我想要比Python& Ruby - 每个时钟周期都很重要。

I'm building an interpreter which I want to be faster than Python & Ruby - every clock cycle matters!

推荐答案

Switch语句通常使用跳转表来实现。我认为大会可以下到一个单一的指令,这将使它很快。

Switch statements are typically implemented with a jump table. I think the assembly can go down to a single instruction, which would make it pretty fast.

唯一的方法是确保是双方尝试。如果您无法修改现有代码,为什么不只是制作测试应用并在那里试用?

The only way to be sure is to try it both ways. If you can't modify your existing code, why not just make a test app and try it there?

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

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