I have a Java method that repeatedly evaluates the following expression in a very tight loop with a large number of repetitions:
Math.abs(a - b) - Math.abs(c - d)
a, b, c and d are long values that can span the whole range of their type. They are different in each loop iteration and they do not satisfy any invariant that I know of.
The profiler indicates that a significant portion of the processor time is spent in this method. While I will pursue other avenues of optimization first, I was wondering if there is a smarter way to calculate the aforementioned expression.
Apart from inlining the Math.abs() calls manually for a very slight (if any) performance gain, is there any mathematical trick that I could use to speed-up the evaluation of this expression?
I ended up using this little method:
I experienced a measurable performance increase – about 10-15% for the whole application. I believe this is mostly due to:
The elimination of a method call: Rather than calling
Math.abs()twice, I call this method once. Sure, static method calls are not inordinately expensive, but they still have an impact.The elimination of a couple of negation operations: This may be offset by the slightly increased size of the code, but I’ll happily fool myself into believing that it actually made a difference.
EDIT:
It seems that it’s actually the other way around. Explicitly inlining the code does not seem to impact the performance in my micro-benchmark. Changing the way the absolute values are calculated does…