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

后端 未结 7 1563
深忆病人
深忆病人 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:12

    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.

提交回复
热议问题