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

前端 未结 5 1820
天涯浪人
天涯浪人 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:02

    I suppose it depends on the implementation, but Math.abs could be as simple as:

    function abs(x) {
        return x < 0 ? x * -1 : x;
    }
    

    So, in theory, it just adds a quick test before multiplying.

    But, yes, negating a negative sign is the sole purpose. The point is that a simple x * -1 is also counter-productive for positive values.


    @olliej [comments]

    True. Simple edit, though. ;)

    function abs(x) {
        return Number(x < 0 ? x * -1 : x);
    }
    

提交回复
热议问题