Math.abs() discussion

mucho kudos for that algorithm, When I saw your usage of 0xFF at the end, I expected it to only work for the specific case of the cap being 2^n-1.
However, on closer inspection, it works in all cases.

if you replace the 255’s, and 0xFF with ‘max’, you have yourself a pretty complete method implementation!

Very funky.

Is there any documentation that shows what are the optimizations done by the latest java compiler? I want to know the exact conditions that will trigger an optimization if this is possible. Since the JIT optimizes the code at runtime this is not as easy as a static compiler that optimizes the code in compilation time.

I know it’s hard to believe, but I have just come across a Math.abs() bottleneck in my game code, specifically when I have lots of physics obejcts bouncing around, the object to object collision check does a first/quick Manhattan (Lm) distance check. This is basically like an Axis-Aligned Bounding Box check but without the box. Anyway, Manhattan distance uses the absolute value difference between points. I’m doing allot to keep from doing more expensive tests and BOOM! profiler shows the test as second highest method call!

I should mention I am using floats, so the little bit hacks don’t help here, but I am trying several tests…

Well at least in the NetBeans profiler…
x = ( x > 0 ) ? x : -x;

is faster than

x = Math.abs(x);

Could be a lie though because the profiling might prevent the VM optimizations for Math.abs()…

[Last mod of the night]

of course…
if ( x < 0 ) { x = -x; }

is faster than

x = ( x > 0 ) ? x : -x;

Because half the time (in general) there will be no asignment done (i.e. x > 0) so i ended with that.

I’ve GOT to stop betting my lungs. :-\

And what about

if(a < 0) {
a *= -1;}

Of course there are bit hacks that would change sign of float point number on SSE2 registers. The bad thing is they would need support from JVM.

and XMM0, const1 // change sign of 4 floats, or 2 doubles to positive.
xor XMM0, const2

I’m 95% sure that this is the case. I have seen getters/setters to be reported by profilers as a bottlenecks, while in real run, they were perfectly inlined. I’ll doublecheck that, but I think that Math.abs should be intrinsic (sp?) and do not invoke any method call at all during normal run.

Edit:
I have doublechecked in mustang code and abs is generated inline - as one single fabs opcode under i486. I’m afraid that any profiling reporting it as a method call is not really right…

I wasn’t using any profilers in any of my tests…