Canvas State Changes

JavaScript performance comparison

Test case created by Tim Schaub and last updated

Preparation code

<canvas id="c" width="1000" height="1000"></canvas>
<script>
var canvas = document.getElementById('c'),
    context = canvas.getContext('2d'),
    numLines = 100,
    numVerts = 20;

function setStyle() {
  context.globalAlpha = 0.5 + 0.5 * Math.random();
  context.fillStyle = '#ffccaa';
  context.strokeStyle = '#ff3300';
  context.lineWidth = Math.ceil(3 * Math.random());
}
function rand() {
  return 1000 * Math.random();
}
</script>
<script>
Benchmark.prototype.setup = function() {
    context.clearRect(0, 0, canvas.width, canvas.height);
};
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
One state change, one path
setStyle();
context.beginPath();
for (var i=0; i<numLines; ++i) {
  context.moveTo(rand(), rand());
  for (var j=0; j<numVerts; ++j) {
    context.lineTo(rand(), rand());
  }
}
context.stroke();
pending…
One state change, many paths
setStyle();
for (var i=0; i<numLines; ++i) {
  context.beginPath();
  context.moveTo(rand(), rand());
  for (var j=0; j<numVerts; ++j) {
    context.lineTo(rand(), rand());
  }
  context.stroke();
}
pending…
Many state changes, many paths
for (var i=0; i<numLines; ++i) {
  setStyle();
  context.beginPath();
  context.moveTo(rand(), rand());
  for (var j=0; j<numVerts; ++j) {
    context.lineTo(rand(), rand());
  }
  context.stroke();
}
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