Hi This was the question asked in my interview Which one is faster in java and why?
Math.max(a,b);
(a>b)?a:b
Hi This was the question asked in my interview Which one is faster in java and why?
Math.max(a,b);
(a>b)?a:b
Math.max(a, b)
is a static function (meaning no virtual call overhead) and will likely be inlined by the JVM to the same instructions as (a > b) ? a : b
.
Here is the code for Math.max()
in Java:
public static int max(int a, int b) {
return (a >= b) ? a : b;
}
So, the code would probably be (almost) exactly the same speed.
(Lets be honest, if you are worrying about speed improvements at such a low level, you probably have far greater problems in your code.)
Not the same. When you are writing (a > b) ? a : b
you don't have an extra function call, so it will be faster. It's the equivalent of inlining in C++.
But this will not make any difference in real life. Math.max(a,b)
is more readable so I would use it.
Performance questions always call for a test before you can start speculating:
public static void maxtest()
{
int res = 0;
for( int idx = 0; --idx != 0; )
// res = ( res > idx ) ? res : idx;
res = Math.max( res, idx );
System.out.println( "res: " + res );
}
This runs on my machine 6 seconds with Math.max()
and 3.2 seconds with ?:
on the latest 1.6.1 x64 server Sun JVM. So ?:
is actually faster. Contrary to all the hopes we like to put in the JITs that have really become amazing by the time they still don't catch everything.
EDIT: Out of curiosity I also tried this code with the 32 bit client JVM 1.6.1 on the same machine and with this both versions run in 7 seconds! So it's probably not the method invocation that doesn't get inlined but the server JIT seems to be able to do some additional optimizations for this particular test case that it can't detect when there is a method call involved.
I've been on the receiving end of this type of question and they are usually more about how you answer the question than what the 'correct' answer is.
If I had asked such a question in an interview, I would have expected the candidate to tell me that the two expressions may not give the same result for all possible types of a and b.
The original question doesn't specify the type of the arguments. This matters because the definition of max (and min) for floating point arguments is more complex. For floating point (double or float) the Math.max method is likely to be slower, but it also may return a different result if one of the arguments is NaN.