Why is the new function (code) faster than directly executing the same code?

I have been comparing the runtime between eval(code)

and new Function(code)


And I found that it is new Function(code)

faster than executing the same code directly.

What is the reason?

var start = new Date().getTime();

var test = ''; for (var i = 0; i < 1000000; ++i) { test += 'a'; }

var end = new Date().getTime();

console.log('Execution time: ' + (end - start));

// vs.

var start2 = new Date().getTime();

var f = new Function("var test = ''; for (var i = 0; i < 1000000; ++i) { test += 'a'; }");


var end2 = new Date().getTime();

console.log('Execution time: ' + (end2 - start2));

Run codeHide result


source to share

1 answer

It actually has nothing to do with the fact that you are creating a function, but rather in the scope of a variable test


Accessing global variables in JavaScript is much slower than accessing local area networks because of the scope chaining - just type, since JavaScript is a dynamic language, every time you use a symbol in your code test

, the JS engine has to "look for it" and see this symbol actually represents (where it is defined). In this search, globals are the last place it looks. Therefore, accessing a local variable is much faster than accessing a global variable.

In the first part of your code, the variable test

is global, and therefore each iteration of the loop requires a full search from the interpreter to find it. However, in the function you have defined it is test

overridden locally, which greatly speeds up access.

Here's a jsperf slug that shows it.



All Articles