Is Javascript “caching” operations?

我们两清 提交于 2021-02-20 18:03:07

问题


I was implementing the Levenshtein distance function in Javascript, and I was wondering how much time it takes to run it with Wikedia's example ("sunday" & "saturday").

So I used console.time() and console.timeEnd() to determine the time spent for the function execution.

for (var i = 0; i < 15; i++) {
    console.time("benchmark" + i);
    var result = LevenshteinDistance("sunday", "saturday");
    console.timeEnd("benchmark" + i);
}

Since it was fluctuating between 0.4ms and 0.15ms, I used a loop and I stumbled upon weird values:

  • 0.187ms
  • 0.028ms
  • 0.022ms
  • 0.022ms
  • 0.052ms
  • 0.026ms
  • 0.028ms
  • 0.245ms
  • 0.030ms
  • 0.024ms
  • 0.020ms
  • 0.019ms
  • 0.059ms
  • 0.039ms
  • 0.040ms

The recurring thing is the high value for the first (and rarely second) execution, then smaller values. (Same behavior between JS in Chrome console and NodeJS.)

So my question is : Is Javascript "caching" executions (since JS is compiled with the V8 engine) ?

And also, can I use this behavior to make the function run faster when using different parameters each time ?


回答1:


V8 is using a JIT compiler. It starts to compile everything as fast as it can with little optimizations because it wants to start quickly and then it optimizes the functions that are called multiple times to speed up the execution where it actually matters.

Why doesn't it optimize everything to begin with? To start faster. Some code is run only once and it would be a waste of time to optimize it because the time of running optimizations would be longer than the time saved by the optimizations. And JavaScript starts pretty quickly - compare running a Node.js hello world to compiling and running a Java hello world (yes, Node.js apps are compiled from scratch every time they start).

Consider this Node.js program, hello.js:

console.log('Hello from Node');

and this Java program, Hello.java:

class Hello {
    public static void main(String[] argv) {
        System.out.println("Hello from Java");
    }
}

Run the Node program:

$ time (node hello.js)
Hello from Node

real    0m0.059s
user    0m0.047s
sys 0m0.012s

and compare it with Java program:

$ time (javac Hello.java && java Hello)
Hello from Java

real    0m0.554s
user    0m1.073s
sys 0m0.068s

For more info see:

  • http://thibaultlaurens.github.io/javascript/2013/04/29/how-the-v8-engine-works/
  • https://v8project.blogspot.com/2015/07/digging-into-turbofan-jit.html
  • http://jayconrod.com/posts/54/a-tour-of-v8-crankshaft-the-optimizing-compiler


来源:https://stackoverflow.com/questions/42631226/is-javascript-caching-operations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!