3

I've got this problem I have been working on and found some interesting behavior. Basically, if I benchmark the same code multiple times in a row, the code execution gets significantly faster.

Here's the code:

http://codepen.io/kirkouimet/pen/xOXLPv?editors=0010

Here's a screenshot from Chrome:

enter image description here

Anybody know what's going on?

I'm checking performance with:

var benchmarkStartTimeInMilliseconds = performance.now();
...
var benchmarkEndTimeInMilliseconds = performance.now() - benchmarkStartTimeInMilliseconds;
3
  • Specifically, it looks like the execution sees a jump in speed after the third iteration in each browser. Commented Jul 9, 2016 at 23:17
  • Google "just in time" compilation/optimization. Commented Jul 9, 2016 at 23:20
  • Just like fine wine...gets better with age (supposed to anyway) Commented Jul 9, 2016 at 23:50

1 Answer 1

4

Chrome's V8 optimizing compiler initially compiles your code without optimizations. If a certain part of your code is executed very often (e.g. a function or a loop body), V8 will replace it with an optimized version (so called "on-stack replacement").

According to 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

Other modern JS engines identify such hotspots and optimize them as well, in a similar fashion.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.