eval vs. script (v6)

Revision 6 of this benchmark created by John-David Dalton on


Preparation HTML

<script>
var JS = 'function fibonacci(n) {\
  if (n < 2) {\
    return 1;\
  } else {\
    return fibonacci(n-2) + fibonacci(n-1);\
  }\
}';

setTimeout(function() {
  var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  var text = JS.replace(/fibonacci/g, 'fibonacciScript');

  try {
    script.appendChild(document.createTextNode(text));
  } catch(e) {
    // for IE
    script.text = text;
  }
  head.appendChild(script);

  eval(JS.replace(/fibonacci/g, 'fibonacciEval'));
  window.fibonacciEval = fibonacciEval;

  window.eval(JS.replace(/fibonacci/g, 'fibonacciIndirectEval'));
  window.fibonacciIndirectEval || (window.fibonacciIndirectEval = fibonacciIndirectEval);
}, 10);

// define after benchmarks have been added
setTimeout(function() {
  // Function One test
  ui.benchmarks[2].setup = function() {
    var fibonacciFn1 = Function('n','\
      if (n < 2) {\
        return 1;\
      } else {\
        var fibonacciFn1 = arguments.callee;\
        return fibonacciFn1(n-2) + fibonacciFn1(n-1);\
      }\
    ');
  };

  // Function Two test
  ui.benchmarks[3].setup = function() {
    var fibonacciFn2 = Function(JS.replace(/fibonacci/g,
      'fibonacciFn2') + 'return fibonacciFn2')();
  };

  // Normal test
  ui.benchmarks[4].setup = function() {
    function fibonacci(n) {
      if (n < 2) {
        return 1;
      } else {
        return fibonacci(n-2) + fibonacci(n-1);
      }
    }
  };
}, 10);
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
eval
fibonacciEval(20);
ready
Script
fibonacciScript(20);
ready
Function One
fibonacciFn1(20);
ready
Function Two
fibonacciFn2(20);
ready
Normal
fibonacci(20);
ready
Indirect eval
fibonacciIndirectEval(20);
ready

Revisions

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

  • Revision 1: published by Devon Govett on
  • Revision 4: published by John-David Dalton on
  • Revision 5: published by Michael Ficarra on
  • Revision 6: published by John-David Dalton on