Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Math.max(a,b) or (a>b)?a:b faster in Java?

Tags:

java

core

Which one is faster in Java and why?

  1. Math.max(a,b)
  2. (a>b)?a:b

(This was asked in an interview.)

like image 870
giri Avatar asked Jan 20 '10 17:01

giri


People also ask

What is time complexity of Math Max?

The time complexity of comparating two elements is O(m), so the complexity of min() and max() is O(m).

What does Math Max do in Java?

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.

Is Math min slow?

Using Math. Min in a loop is almost 4 times slower than before.

Is Max () a Math method?

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 .


2 Answers

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.

like image 196
dsimcha Avatar answered Sep 24 '22 03:09

dsimcha


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.)

like image 33
jjnguy Avatar answered Sep 23 '22 03:09

jjnguy