在Javascript中使数字为负的最便宜的方法

Cheapest way of making a number negative in Javascript

本文关键字:最便宜 方法 数字 Javascript      更新时间:2023-09-26

我正在优化我在javascript中制作的物理引擎。我一直在阅读一些关于与cpu使用相关的操作成本的文章,但我找不到这个问题的答案。我想做一个"否定"。我想出了两个不同的解决方案:

a *= -1;

a = -a;

哪一个是最快的?我读到乘法很便宜,但这些方法中哪一种是最好的?

似乎过度优化了。

我将选择second,因为它很短

a*=-1; //5
a=-a;  //4

我已经执行了一个小测试。结果:没关系!

<!DOCTYPE HTML>
<html>
<body>
  <script>
    var a = 123.21; 
    var start = new Date().getTime(); // time in milliseconds
    for(var i = 0; i < 1000000000;  i++) {
        //a = -a;    
        // results into time needed: 2002 ms when a is integer, 3505 ms when a is floating point
        a *= -1; 
        // results into time needed: 1992 ms when a is integer, 3671 ms when a is floating point
    }
    var end = new Date().getTime();
    var time = end - start;
    alert("time needed: "+time);
  </script>
</body>
</html>

不用猜了:http://jsperf.com/prefix-speed有答案

根据Chrome浏览器的这个测试,差异是无法区分的。