我需要将 int 值 1,2,3 映射到字符 'C', 'M', 'A'
最快的方法是什么(这将被称为每秒 100 次 24/7)?
宏或内联函数和一堆 ?: 运算符或 ifs 或 switch?或者一个数组?
查找表似乎是最明显的方法,因为它也是无分支的:
constexpr char map(std::size_t i) {
constexpr char table[] = "0CMA";
// if in doubt add bounds checking for i, but it will cost performance
return table[i];
}
Run Code Online (Sandbox Code Playgroud)
观察到,通过优化,查找表可以归结为整数常量。
编辑:如果你没有我那么懒,你可以删除额外的指令并指定查找表:
constexpr char table[] = {0, 'M', 'C', 'A'};
Run Code Online (Sandbox Code Playgroud)