Does eval 'spoil' a scope

JavaScript performance comparison

Revision 2 of this test case created by Marijn

Info

Lexical eval can be statically detected, and must have access to local variables in the scope where it is executed. This tries to test whether browsers add any performance overhead to scopes that have an eval in them -- the benchmark's cost is mostly regular code, with a trivial eval thrown in to the second case.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    function regular(s) {
      for (var o = 0, i = 1e7, j = 0; i >= 0; --i, ++j)
        o += j - i;
      s;
      return o;
    }
   
    function spoiled(s) {
      for (var o = 0, i = 1e7, j = 0; i >= 0; --i, ++j)
        o += j - i;
      eval(s);
      return o;
    }
   
    function spoiledInBranch(s) {
      for (var o = 0, i = 1e7, j = 0; i >= 0; --i, ++j)
        o += j - i;
      if (s == "nope") eval(s);
      return o;
    }
   
    function spoiledStrict(s) {
      "use strict";
      for (var o = 0, i = 1e7, j = 0; i >= 0; --i, ++j)
        o += j - i;
      eval(s);
      return o;
    }
   
    function spoiledInner(s) {
      for (var o = 0, i = 1e7, j = 0; i >= 0; --i, ++j)
        o += j - i;
      function inner() { eval(s); }
      inner();
      return o;
    }
   
    function spoiledOuter(s) {
      function inner() {
        for (var o = 0, i = 1e7, j = 0; i >= 0; --i, ++j)
          o += j - i;
      }
      var o = inner();
      eval(s);
      return o;
    }
};
</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
Regular
regular(String(Math.random()));
pending…
Spoiled
spoiled(String(Math.random()));
pending…
Spoiled inner function
spoiledInner(String(Math.random()));
pending…
Spoiled outer function
spoiledOuter(String(Math.random()));
pending…
Spoiled in inactive branch
spoiledInBranch(String(Math.random()));
pending…
Spoiled in strict mode
spoiledStrict(String(Math.random()));
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment