为什么 JavaScript 代码随着时间的推移执行得更快?
Why does JavaScript code execute faster over time?
我一直在处理这个问题,并发现了一些有趣的行为。基本上,如果我连续多次对同一代码进行基准测试,代码执行速度会明显加快。
代码如下:
http://codepen.io/kirkouimet/pen/xOXLPv?editors=0010
这是来自 Chrome 的屏幕截图:
有人知道发生了什么事吗?
我正在检查性能:
var benchmarkStartTimeInMilliseconds = performance.now();
...
var benchmarkEndTimeInMilliseconds = performance.now() - benchmarkStartTimeInMilliseconds;
Chrome 的 V8 优化编译器最初编译您的代码 没有优化 。如果您的代码的某个部分执行得非常频繁(例如函数或循环体),V8 将用 优化 版本(所谓的 "on-stack replacement")替换它。
根据https://wingolog.org/archives/2011/06/08/what-does-v8-do-with-that-loop:
V8 always compiles JavaScript to native code. The first time V8 sees a
piece of code, it compiles it quickly but without optimizing it. The
initial unoptimized code is fully general, handling all of the various
cases that one might see, and also includes some type-feedback code,
recording what types are being seen at various points in the
procedure.
At startup, V8 spawns off a profiling thread. If it notices that a
particular unoptimized procedure is hot, it collects the recorded type
feedback data for that procedure and uses it to compile an optimized
version of the procedure. The old unoptimized code is then replaced
with the new optimized code, and the process continues
其他现代 JS 引擎识别此类热点并以类似的方式对其进行优化。
我一直在处理这个问题,并发现了一些有趣的行为。基本上,如果我连续多次对同一代码进行基准测试,代码执行速度会明显加快。
代码如下:
http://codepen.io/kirkouimet/pen/xOXLPv?editors=0010
这是来自 Chrome 的屏幕截图:
有人知道发生了什么事吗?
我正在检查性能:
var benchmarkStartTimeInMilliseconds = performance.now();
...
var benchmarkEndTimeInMilliseconds = performance.now() - benchmarkStartTimeInMilliseconds;
Chrome 的 V8 优化编译器最初编译您的代码 没有优化 。如果您的代码的某个部分执行得非常频繁(例如函数或循环体),V8 将用 优化 版本(所谓的 "on-stack replacement")替换它。
根据https://wingolog.org/archives/2011/06/08/what-does-v8-do-with-that-loop:
V8 always compiles JavaScript to native code. The first time V8 sees a piece of code, it compiles it quickly but without optimizing it. The initial unoptimized code is fully general, handling all of the various cases that one might see, and also includes some type-feedback code, recording what types are being seen at various points in the procedure.
At startup, V8 spawns off a profiling thread. If it notices that a particular unoptimized procedure is hot, it collects the recorded type feedback data for that procedure and uses it to compile an optimized version of the procedure. The old unoptimized code is then replaced with the new optimized code, and the process continues
其他现代 JS 引擎识别此类热点并以类似的方式对其进行优化。