tag-vs-eval-fn-construction

JavaScript performance comparison

Test case created and last updated

Preparation code

<script>
var createScriptFunction = function(args, body) {
  var prevDash = window._,
      script = document.createElement('script'),
      sibling = document.scripts[0];

  script.text = 'var _ = function(' + args + ') {' + body + '\n}';
  sibling.parentNode.insertBefore(script, sibling).parentNode.removeChild(script);

  var result = window._;
  window._ = prevDash;
  return result;
};

try {
  createScriptFunction();
} catch(e) {
  createScriptFunction = Function;
}

var createEvalFunction = function(args, body) {
  return eval('(function(' + args + ') {' + body + '\n})');
};
</script>
<script>
Benchmark.prototype.setup = function() {
    var createScriptFunction = window.createScriptFunction;
    var createEvalFunction = window.createEvalFunction;
   
    var args = 'array, callback, thisArg';
    var code = [
      'var index = -1,',
      '    length = array.length;',
      'if (typeof thisArg != "undefined") {',
      '  var fn = callback;',
      '  callback = function(value, index, array) {',
      '    return fn.call(thisArg, value, index, array);',
      '  };',
      '}',
      'while (++index < length) {',
      '  if (callback(array[index], index, array) === false) {',
      '    break;',
      '  }',
      '}',
      'return array;'
    ].join('\n');
   
    var scriptFn = createScriptFunction(args, code);
    var evalFn = createEvalFunction(args, code);
    var funcFn = Function(args, code);
    var normalFn = function(array, callback, thisArg) {
      var index = -1,
          length = array.length;
      if (typeof thisArg != "undefined") {
        var fn = callback;
        callback = function(value, index, array) {
          return fn.call(thisArg, value, index, array);
        };
      }
      while (++index < length) {
        if (callback(array[index], index, array) === false) {
          break;
        }
      }
      return array;
    };
   
    var arr = Array(101).join('x').split('');
    var callback = function(value) { return value; };
};
</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
script injection
var r = scriptFn(arr, callback);
pending…
eval
var r = evalFn(arr, callback);
pending…
Function
var r = funcFn(arr, callback);
pending…
normal
var r = normalFn(arr, callback);
pending…

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

Compare results of other browsers

0 comments

Add a comment