I often encounter problem of finding absolute difference of 2 unsigned numbers (lets say usize for example). Obvious way @abs(a - b) won’t work since numbers can overflow.
And each time i find new way to implement it.
fn absdiff1(a: usize, b: usize) usize {
return @max(a, b) - @min(a, b);
}
fn absdiff2(a: usize, b: usize) usize {
if (a > b) {
return a - b;
}
return b - a;
}
fn absdiff3(a: usize, b: usize) usize {
return @max(a -| b, b -| a);
}
fn absdiff4(a: usize, b: usize) usize {
return @min(a -% b, b -% a);
}
// Only works for numbers with known size.
// From mentioned versions it is the only one which uses `a` and `b` expressions once so it is theoretically usable as inline expression.
fn absdiff5(a: u32, b: u32) u32 {
return @intCast(@abs(@as(i33, a) - @as(i33, b)));
}
What do you think is the best way? Can you find new clever ways? Maybe winner should be placed into standard library since its pretty common operation?
I think this is a great exercise and very educational. However, I wouldn’t expect std lib code to be in assembly. Would be nice if the compiler could yield similar assembly code.
Another concern is eye-balling assembler may not be the best approach to judge this kind of code. In real use the code is likely inlined and potentially could be a different implementation depending on the surrounding code it’s inlined with.
Probably better to benchmark in real use and check mature implementations.