函数数组在 if 和 switch 语句上的性能 [英] Performance of array of functions over if and switch statements

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

问题描述

我正在编写代码的一个非常关键的性能部分,我有一个关于用函数指针数组替换 case 语句(或 if 语句)的疯狂想法.

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;
    }
}

这是回调函数"版本:

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]) ();
}

那么哪个版本会更快?函数调用的开销是否消除了比普通 switch(或 if)语句的速度优势?

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.

推荐答案

我认为最终你的 switch 语句将是最快的,因为函数指针有查找函数和函数的开销"称自己.开关只是一个 jmp 表.这当然取决于不同的事情,只有测试才能给你答案.那是我的两分钱.

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天全站免登陆