Which is faster: Math.abs(value) or value * -1 ?

前端 未结 5 1821
天涯浪人
天涯浪人 2020-12-25 11:24

Pretty straightforward, but I just want to know which is faster.

I think simply multiplying a number by -1 is much faster than calling a predefined meth

5条回答
  •  臣服心动
    2020-12-25 11:59

    I would suggest picking the method that more clearly shows your intention, rather than worrying about the performance. In this case, the performance gain of multiplying by -1 is probably minimal.

    When you use Math.abs(), it is very clear that you want a positive value. When you use * -1 it is not clear, and requires more investigation to determine if the input value is always negative.

提交回复
热议问题