Direct vs dynamic property access

JavaScript performance comparison

Test case created by simonbrunel

Preparation code

<canvas id="chart"></canvas>
      
<script>
Benchmark.prototype.setup = function() {
  var ctx = document.getElementById('chart').getContext('2d');
  var f1 = 'bold 12px sans-serif';
  var f2 = 'bold 18px sans-serif';
  var w1 = 12;
  var w2 = 42;
  var p0 = 'font';
  var p1 = 'lineWidth';
  
  function _set(target, prop, value) {
      target[prop] = value;
  }
  
  function _set_and_check(target, prop, value) {
      target[prop] = value;
      if (target[prop] !== value) {
         throw new Error('booom: "' + value + '" is not a valid value for ' + prop);
      }
  }

};
</script>

Preparation code output

<canvas id="chart"></canvas>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Direct access
ctx.font = f1;
ctx.font = f2;
ctx.lineWidth = w1;
ctx.lineWidth = w2;
pending…
Dynamic access
ctx[p0] = f1;
ctx[p0] = f2;
ctx[p1] = w1;
ctx[p1] = w2;
pending…
Dynamic setter
_set(ctx, 'font', f1);
_set(ctx, 'font', f2);
_set(ctx, 'lineWidth', w1);
_set(ctx, 'lineWidth', w2);
pending…
Guarded setter
_set_and_check(ctx, 'font', f1);
_set_and_check(ctx, 'font', f2);
_set_and_check(ctx, 'lineWidth', w1);
_set_and_check(ctx, 'lineWidth', w2);
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