1、前言
前几天与小伙伴讨论了switch-case、if-else孰优孰劣,同时想起了当年有个cpython使用goto来优化switch-case的,性能提升了15-20%。使用的就是 computed goto 方法。
2、使用场景
在Python中有个字节码解释器(Bytecode Interpreter),源码是Python/ceval.c,主要是循环地处理字节流,输入一个char,输出一个计算结果。按参考文章[1],将核心代码模拟出来。
3、代码测试
首先是宏定义、switch-case的实现:
#define OP_HALT 0x0
#define OP_INC 0x1
#define OP_DEC 0x2
#define OP_MUL2 0x3
#define OP_DIV2 0x4
#define OP_ADD7 0x5
#define OP_NEG 0x6
#define OP_MAX 0x7
int bm_dispatch::interp_switch(const uint8_t *code, int initval)
{
int pc = 0;
int val = initval;
while (1) {
switch (code[pc++]) {
case OP_HALT:
return val;
case OP_INC:
val++;
break;
case OP_DEC:
val--;
break;
case OP_MUL2:
val *= 2