且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将变量与多个值进行比较的最有效方法?

更新时间:2023-01-21 11:35:55

如果您要检查的值足够小,您可以创建您要查找的值的位掩码,然后检查要设置的位.

If the values you want to check are sufficiently small, you could create a bit mask of the values that you seek and then check for that bit to be set.

假设您关心几个组.

static const unsigned values_group_1 = (1 << 1) | (1 << 2) | (1 << 3);
static const unsigned values_group_2 = (1 << 4) | (1 << 5) | (1 << 6);
static const unsigned values_group_3 = (1 << 7) | (1 << 8) | (1 << 9);    
if ((1 << value_to_check) & values_group_1) {
  // You found a match for group 1
}
if ((1 << value_to_check) & values_group_2) {
  // You found a match for group 2
}
if ((1 << value_to_check) & values_group_3) {
  // You found a match for group 3
}

这种方法最适合不超过您的 CPU 喜欢使用的自然大小的值.在现代,这通常是 64,但可能会因环境的具体情况而异.

This approach works best for values that don't exceed the natural size your CPU likes to work with. This would typically be 64 in modern times, but may vary depending upon the specifics of your environment.