Opt*_*ard 15 c optimization if-statement callback switch-statement
我正在编写一个非常重要的性能代码部分,我有一个关于用函数指针数组替换case语句(或if语句)的疯狂想法.
让我来证明一下; 这是正常版本:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这里是"回调函数"版本:
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]) ();
}
Run Code Online (Sandbox Code Playgroud)
那么哪个版本会更快?函数调用的开销是否超过了正常的switch(或if)语句的速度优势?
当然后一个版本不是那么可读,但我正在寻找我能得到的所有速度.
当我设置好东西但是如果有人已经有了答案,我就打算对此进行基准测试.
我认为在一天结束时你的switch语句将是最快的,因为函数指针具有查找函数和函数调用本身的"开销".一个开关只是一个jmp表直.它当然取决于不同的东西,只有测试可以给你一个答案.这是我的两分钱.
| 归档时间: |
|
| 查看次数: |
8758 次 |
| 最近记录: |