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

Revision 19 of this benchmark created by Hank Schultz on


Description

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.

This test compares the efficiency of calling functions that have been created via various means. As is shown by other versions of this test where there are loops inside the functions (e.g. version 8), there is little difference in the amount of time it takes to run a function, regardless how it is created. Therefore, the determining factor is how long it takes to initiate the function, which this version will test.

Preparation HTML

<script>
  var fn1 = function() {
   return 1 + 2;
  };
  var fn2 = new Function('return 1 + 2;');
  var fn3 = eval('dummy = function(){return 1 + 2;}');
  var fn4 = new Function('return function () { return 1 + 2; }')();
  
  var script = document.createElement("script");
  script.innerHTML = 'function fn5() {return 1+2;}';
  document.body.appendChild(script);
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Function expression
fn1();
ready
Function constructor
fn2();
ready
A function created with eval()
fn3();
ready
Meta-Function Constructor
fn4();
ready
Creating Script File
fn5();
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.