C语言动态分发:函数指针与switch分支的性能对比及选型
C语言动态分发的性能差异与实现选择
需要动态选择调用两个函数(类似C++虚表的实现逻辑),测试代码如下:
common.h
#include<stdlib.h> #include<time.h> #define TEST_N 100000000 static volatile int state = 0; static void foo1() { state = 1; } static void foo2() { state = 2; }
test1.c
#include"common.h" int foo_choose(){ if (rand()%2 == 0){ return 2; } return 1; } int main(){ time_t t; srand(time(&t)); for(size_t i = 0; i<TEST_N; i++){ switch(foo_choose()){ case 1: foo1(); break; case 2: foo2(); break; } } return 0; }
test2.c
#include"common.h" void (*foo_choose(void))(){ if (rand()%2 == 0){ return &foo2; } return &foo1; } int main(){ time_t t; srand(time(&t)); for(size_t i = 0; i<TEST_N; i++){ (foo_choose())(); } return 0; }
测试现象
ARM64架构下使用Apple Clang(-O1/-O3优化)时,test1的运行速度显著快于test2;而GCC12下无论采用何种优化等级,两者性能相近,查看汇编代码未发现明显差异。
咨询问题
- 为何会出现上述性能差异?
- 在复杂代码场景下,哪种实现方式的性能更优?
- 哪种是C语言动态分发的更优实现?(注:test1灵活性更高,支持非函数指针逻辑)
补充说明
若难以给出定论,可分享分析思路;若性能差异依赖硬件架构,是否存在适配所有架构的通用写法?
内容的提问来源于stack exchange,提问作者Mr User
相关产品推荐
相关产品推荐

