Create functions from strings

Benchmark created by Hanh Pho on


Setup

String.prototype.parseFunction = function () {
        var funcReg = /function *\(([^()]*)\)[ \n\t]*{(.*)}/gmi;
        var match = funcReg.exec(this.replace(/\n/g, ' '));
    
        if(match) {
            return new Function(match[1].split(','), match[2]);
        }
    
        return null;
    };

Test runner

Ready to run.

Testing in
TestOps/sec
Using RegExp with Function class
var func = "function (a, b) { return a + b; }".parseFunction();
ready
Using Function class with "return "
var func = new Function("return " + "function (a, b) { return a + b; }")();
ready
Using official Function constructor
var func = new Function("a", "b", "return a + b;");
ready
Using Eval
eval("var func = function (a, b) { return a + b; };");
ready

Revisions

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