gpt4 book ai didi

javascript - 为什么 for 循环迭代 100000 次比 50000 次更快?

转载 作者:行者123 更新时间:2023-11-28 11:16:06 28 4
gpt4 key购买 nike

我一直在这个页面上绘制 JavaScript 不同方面的性能图表。在尝试以不同的迭代次数绘制简单的 for 循环的过程中,我发现循环的速度似乎在超过 50000 次迭代的某个时刻显着增加,我很想知道为什么。

这是我正在使用的循环:

var oN = function (n)
{
var startTime;
var endTime;
startTime = window.performance.now();
for (var i = 0; i <= n; i++) {};
endTime = window.performance.now() - startTime;
return endTime.toFixed(2);
}

这张图中test的值为n=1000000

最佳答案

显然这里有很多因素,但是this Google 的 Chris Wilson 撰写的有关 Chrome 的两个 JIT 编译器如何工作的文章可能会解释您所看到的部分内容。

特别是:

The Optimizing Compiler

In parallel with the full compiler, V8 re-compiles "hot" functions (that is, functions that are run many times) with an optimizing compiler. This compiler uses type feedback to make the compiled code faster - in fact, it uses the types taken from ICs we just talked about!

In the optimizing compiler, operations get speculatively inlined (directly placed where they are called). This speeds execution (at the cost of memory footprint), but also enables other optimizations. Monomorphic functions and constructors can be inlined entirely (that's another reason why monomorphism is a good idea in V8).

You can log what gets optimized using the standalone "d8" version of the V8 engine:

d8 --trace-opt primes.js

(this logs names of optimized functions to stdout.)Not all functions can be optimized, however - some features prevent the optimizing compiler from running on a given function (a "bail-out"). In particular, the optimizing compiler currently bails out on functions with try {} catch {} blocks!

所以你可以比较你的original ,带有 version inside try {} catch {} blocks以防止优化编译器干扰,您可能会得到更接近您最初预期的结果。

关于javascript - 为什么 for 循环迭代 100000 次比 50000 次更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29336969/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com