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

前端 未结 5 1811
天涯浪人
天涯浪人 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 12:01

    Just the *-1 operation is probably faster, but keep in mind that the end result differs from the result for math.abs().

    math.abs(-5) and math.abs(5) both return 5.

    -5 * -1 returns 5 as well.

    5 * -1 returns -5.

    So unless you're absolutely sure that the number is negative to begin with, you have to do some tests, which cost more time. Might as well do math.abs().

    But really, if the performance difference between abs() and *-1 matters in your JS, your probably have more serious issues.

提交回复
热议问题