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

Revision 10 of this benchmark created by Luigi Grilli 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.

Changed the code so that the functions are created inside of the test scenario and not the preparation code

Setup

var fn1 = function() {
     return 1 + 2;
    };
    
    var fn2 = new Function('return 1 + 2;');
    
    eval('var fn3 = function(){return 1 + 2;}');

Test runner

Ready to run.

Testing in
TestOps/sec
Function expression
for(var i=0; i<10000; i++) {
    fn1();
}
ready
Function constructor
for(var i=0; i<10000; i++) {
    fn2();
}
ready
A function created with eval()
for(var i=0; i<10000; i++) {
    fn3();
}
ready

Revisions

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