首页 > 解决方案 > 将 2 个整数与另外 2 个整数进行有效比较

问题描述

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

基本上,我有 2 个整数cm. 比较两个对象首先需要检查双方是否相等,然后比较取决于它们的c值。cm

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;

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

谢谢

标签: c#performanceoptimizationbit-manipulationmathematical-optimization

解决方案


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

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

所以我们首先比较ms,然后通过 s 的比较覆盖它,利用cs 的有限范围m


推荐阅读