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

后端 未结 7 1562
深忆病人
深忆病人 2020-12-03 20:59

Which one is faster in Java and why?

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

(This was asked in an interview.)

7条回答
  •  北海茫月
    2020-12-03 21:08

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

提交回复
热议问题