3

function* test() {
  console.time("function-call")
  loop();
  console.timeEnd("function-call");

  console.time("in-function");
  var i, j;
  i = 0;
  while (i < 10000) {
    j = 0;
    while (j < 10000) {
      j++
    }
    i++;
  }
  console.timeEnd("in-function");
}

function loop() {
  var i, j;
  i = 0;
  while (i < 10000) {
    j = 0;
    while (j < 10000) {
      j++
    }
    i++;
  }
}

test().next();

我复制了“循环”中的代码块,并粘贴到“测试”函数中以比较时间。

function-call: 84ms 
in-function: 596ms

调用函数比在函数内部循环要快得多。为什么呢?

4

1 回答 1

1

@Cristian Traìna Node 不允许跳过空循环。这些优化只允许在编译语言(如 Pascal 或 C/C++)中使用-O2.

对于这个程序

var max=process.argv[2];
for(var i=0;i<=max;i++){} // with let results is the same

我们可以从许多循环中获得以下执行时间的依赖性。它是一个 LogLog 图表。它支配部分执行时间的第一个平坦区域是 NodeJs 的启动。在 1M 循环之后,您可以看到迭代次数随时间线性增加。最高测量大约需要 1000 秒,因此 V8 不会跳过空循环。


(来源:gustawdaniel.pl

从问题回到脚本:

  • 铬 71.0.3578.98
function-call: 154.878662109375ms
in-function: 153.7490234375ms
  • 节点 v10.15.0
function-call: 154.183ms
in-function: 152.907ms
  • 火狐量子 64.0
function-call: 156 ms debugger eval code:4:3
in-function: 1519 ms
  • 铬 71.0.3578.98
function-call: 158.954345703125ms
in-function: 153.663818359375ms
  • 维瓦尔第 2.2
function-call: 153.548095703125ms
in-function: 153.755126953125ms
  • 歌剧 58.0.3135.47
function-call: 154.34814453125ms
in-function: 154.729248046875ms

我朋友的电脑测试:

  • 边缘
function-call: 3 496,6 ms
in-function: 2 330,9 ms
  • 铬合金
function-call: 70.69580078125ms
in-function: 70.43310546875ms

所以现在这似乎是 Firefox 和 Edge 的问题。

除了 Firefox 和 Edge 之外,这些浏览器中的任何一个都使用 V8 引擎。火狐在这里描述:

https://www.digitaltrends.com/web/mozilla-firefox-new-browser-engine-quantum-2017/

并使用Quantum Flow:.

Edge 团队考虑采用 Chromium 引擎

https://www.pcmag.com/news/365345/microsofts-edge-browser-to-adopt-googles-chromium-engine

从这篇文章

https://blog.mozilla.org/blog/2018/12/06/goodbye-edge/

我们只能看到这一点Chromium from GoogleGecko Quantum from Mozilla并将在未来得到支持。

如果有人可以访问 Safari 或 Edge,请附加测试。

于 2019-01-24T12:26:47.650 回答