3

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));

2
  • @Sirko: my bad. :) But after the edit, the second version still seems faster Commented Sep 27, 2014 at 18:46
  • I believe it is because JavaScript is single threaded Commented Sep 27, 2014 at 19:08

1 Answer 1

4

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.

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

1 Comment

Here's an updated test case that doesn't show the huge difference any more.

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.