I have a piece of code used for comparison which is in a hot path being called millions of times. After benchmarking, that piece of code is a candidate for optimization.
Basically, I have 2 integers c
and m
. Comparing two objects involves first checking c
then if c
is equal on both sides, then comparison is decided by their m
value.
c
can only be in the range [0-100]
m
can only be in the range [0-200]
pseudo code
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;
The following C# code is what I currently have
int CompareTo(Obj other)
=> _c < other._c || (_c == other._c && _m < other._m)
? -1
: _c == other._c && _m == other._m
? 0
: 1;
I am wondering if this could be optimized any further, perhaps with bit-manipulation?
Thanks
c
can only be in the range[0-100]
m
can only be in the range[0-200]
Given the ranges, each of c, m
fit into a single (unsigned) byte, so they can be packed together into an integer cm = c * 256 + m
, or cm = (c << 8) | m
using only bitwise ops.
Since only the sign of the compare function matters (as clarified in a comment), two such integers can then be compared by direct subtraction.
int CompareTo(Obj other) => ((_c << 8) | _m) - ((other._c << 8) | other._m)
The above is branchless and uses only bitwise/arithmetic operators, so it should fare well against nested comparisons for most distributions of c, m
values.