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

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

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

提交回复
热议问题