function(){} vs new Function() vs eval(function(){})

JavaScript performance comparison

Test case created by curiousdannii

Info

https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope says

Functions defined by function expressions and function declarations are parsed only once, while those defined by the Function constructor are not. That is, the function body string passed to the Function constructor must be parsed every time it is evaluated. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than "new Function(...)". Therefore the Function constructor should be avoided whenever possible.

Which sounds bad.

Preparation code

<script>
  var fn1 = function() {
   return 1 + 2;
  };
  var fn2 = new Function('return 1 + 2;');
  var fn3 = eval('dummy = function(){return 1 + 2;}');
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Function expression
fn1();
pending…
Function constructor
fn2();
pending…
A function created with eval()
fn3();
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment