简体   繁体   中英

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

I was comparing the execution times between eval(code) and new Function(code) .

And I discovered that new Function(code) is faster than directly execute the same code.

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'; }"); f(); var end2 = new Date().getTime(); console.log('Execution time: ' + (end2 - start2)); 

This actually has nothing to do with the fact that you're creating a function, but rather with the scope of the test variable.

Accessing globals in JavaScript is much slower than accessing locals because of the scope chain - simply put, since JavaScript is a dynamic language, every time you use a symbol called test in your code, the JS engine needs to "look it up" and see what that symbol actually represents (where it's defined). In this lookup, global variables 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 a global and thus every iteration of the loop needs a full lookup from the interpreter to find it. However, in the function you defined, test is redefined locally, making it much faster to access.

Here's a jsperf slug that shows this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM