Which one is faster in Java and why?
Math.max(a,b)
(a>b)?a:b
(This was asked in an interview.)
Do not rely on speculation. Instead, benchmark your particular use case.
Some easily overlooked details in many of the other answers:
While you can see a Java source of Math.max
, this is actually not always what will be used. This method has an intrinsic version in pretty much every JRE. See the source code of Hotspot in JDK7, vmSymbols.hpp for a list of such intrinsics.
As far as I can tell, Hotspot will try a number of optimizations when it sees a max
or min
statement; in particular to optimize e.g. arraycopy
. Amongst others, it will actually optimize Math.max(same, same)
away.
In other cases, however, it may not optimize much; (a<=b)?a:b
may then actually be faster. I've been benchmarking a bit, and indeed I often found this to be faster. But YMMV, and it definitely depends on the context if Hotspot can optimize one better or the other. It will also vary from hotspot version to hotspot version...