功能阵列性能超过if和switch语句 [英] Performance of array of functions over if and switch statements

查看:128
本文介绍了功能阵列性能超过if和switch语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了code的表现非常关键的部分,我有大约替代case语句(或if语句)函数指针数组这个疯狂的想法。

让我证明;这里去普通版:

 而(陈述)
{
    / *选项在每次迭代变化* /    开关(可选)
    {
        案件0:/ *简单的任务* /休息;
        案例1:/ *简单的任务* /休息;
        案例2:/ *简单的任务* /休息;
        案例3:/ *简单的任务* /休息;
    }
}

和这里是回调函数的版本:

 无效task0(无效){
    / *简单的任务* /
}无效独立写作(无效){
    / *简单的任务* /
}TASK2无效(无效){
    / *简单的任务* /
}无效TASK3(无效){
    / *简单的任务* /
}无效(*任务[4])(无效);任务[0] = task0;
任务[1] =任务1;
任务[2] = TASK2;
任务[3] = TASK3;而(陈述)
{
    / *选项在每次迭代变化* /    / *现在我们所说的用案例号码的功能* /
    (*任务[选项])();
}

所以哪个版本会更快?是函数调用消除了普通开关(或)语句?

速度益处的开销

Ofcourse后者的版本是不是这样读,但是我找了所有的速度,我可以得到。

我要这个基准时,我得到的东西成立,但如果有人有一个答案已经,我不会理会。

解决方案

我觉得在这一天结束的switch语句将是最快的,因为函数的指针都具有的功能和作用的查找的开销调用自己。开关只是一个JMP表直。它当然的取决于在不同的东西,只有测试可以给你一个答案。这是我的两个美分的价值。

I am writing a very performance critical part of the code and I had this crazy idea about substituting case statements (or if statements) with array of function pointers.

Let me demonstrate; here goes the normal version:

while(statement)
{
    /* 'option' changes on every iteration */

    switch(option)
    {
        case 0: /* simple task */ break;
        case 1: /* simple task */ break;
        case 2: /* simple task */ break;
        case 3: /* simple task */ break;
    }
}

And here is the "callback function" version:

void task0(void) {
    /* simple task */
}

void task1(void) {
    /* simple task */
}

void task2(void) {
    /* simple task */
}

void task3(void) {
    /* simple task */
}

void (*task[4]) (void);

task[0] = task0;
task[1] = task1;
task[2] = task2;
task[3] = task3;

while(statement)
{
    /* 'option' changes on every iteration */

    /* and now we call the function with 'case' number */
    (*task[option]) ();
}

So which version will be faster? Is the overhead of the function call eliminating speed benefit over normal switch (or if) statement?

Ofcourse the latter version is not so readable but I am looking for all the speed I can get.

I am about to benchmark this when I get things set up but if someone has an answer already, I wont bother.

解决方案

I think at the end of the day your switch statements will be the fastest, because function pointers have the "overhead" of the lookup of the function and the function call itself. A switch is just a jmp table straight. It of course depends on different things which only testing can give you an answer to. That's my two cent worth.

这篇关于功能阵列性能超过if和switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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