Which one is faster in Java and why?
Math.max(a,b)
(a>b)?a:b
(This was asked in an interview.)
The time complexity of comparating two elements is O(m), so the complexity of min() and max() is O(m).
max(int a, int b) returns the greater of two int values. That is, the result is the argument closer to positive infinity. If the arguments have the same value, the result is that same value.
Using Math. Min in a loop is almost 4 times slower than before.
Description. Because max() is a static method of Math , you always use it as Math. max() , rather than as a method of a Math object you created ( Math is not a constructor). If no arguments are given, the result is - Infinity .
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 openjdk 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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With