2个整数与另一个2的有效比较



我有一段用于比较的代码,它位于被调用数百万次的热路径中。在基准测试之后,这段代码就是优化的候选代码。

基本上,我有两个整数cm。比较两个对象首先检查c,然后如果c在两侧相等,则比较由它们的m值决定。

c只能在[0-100]范围内

m只能在[0-200]范围内

伪码

if this.c < other.c return -1; // Or any negative number
if this.c > other.c return 1;  // Or any positive number
// Both objects have equal 'c' value
if this.m < other.m return -1; // Or any negative number
if this.m > other.m return 1;  // Or any positive number
// Both 'c' and 'm' are equal
return 0;

下面的C#代码是我目前拥有的

int CompareTo(Obj other)
=> _c < other._c || (_c == other._c && _m < other._m)
? -1
: _c == other._c && _m == other._m
? 0
: 1;

我想知道这是否可以进一步优化,也许可以通过比特操作?

感谢

比dxiv的版本略短,但基于相同的想法:

(this.m - other.m) + ((this.c - other.c) << 8)

因此,我们首先比较ms,然后通过比较cs来覆盖它,利用ms的有限范围。

c只能在[0-100]范围内
m只能在[0-200]范围内

给定范围,每个c, m都适合一个(无符号(字节,因此它们可以一起打包为整数cm = c * 256 + mcm = (c << 8) | m,只使用逐位操作。

由于只有比较函数的符号很重要(如注释所述(,因此可以通过直接减法来比较两个这样的整数。

int CompareTo(Obj other)  =>  ((_c << 8) | _m) - ((other._c << 8) | other._m)

上面的是无分支的,并且只使用逐位/算术运算符,因此对于大多数c, m值的分布,它应该可以很好地进行嵌套比较。

最新更新