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

giri picture giri · Jan 20, 2010 · Viewed 14.3k times · Source

Which one is faster in Java and why?

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

(This was asked in an interview.)

Answer

dsimcha picture dsimcha · Jan 20, 2010

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.