【发布时间】:2010-04-19 00:44:54
【问题描述】:
- 哪个更快:函数指针还是开关?
switch 语句大约有 30 个cases,由从 0 到 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 个函数更有条理。
或者我可以这样做(不太确定):
class myType
{
myReturnType (*func)(int all, int of, int my, int args );
string argv[123];
int someOtherValue;
};
然后,我将有 30 个不同的函数,一开始将指向其中一个的指针分配给 myType。
- 什么可能更快:Switch 语句或函数指针?
每秒调用次数:大约 1000 万次。 我不能只是测试它——那需要我重写整个事情。目前正在使用开关。
我正在构建一个解释器,我希望它比 Python 和 Ruby 更快 - 每个时钟周期都很重要!
【问题讨论】:
-
你的意思是
myReturnType (*func)();? -
"我正在构建一个解释器" 经典的解决方案是计算 goto:eli.thegreenplace.net/2012/07/12/…
标签: c++ performance