Canvas state change test

Benchmark created on


Preparation HTML

<canvas width="800px" height="800x"></canvas>

Setup

var canvas = document.getElementsByTagName('canvas')[0],
      ctx = canvas.getContext('2d'),
      tileWidth = 8,
      tilesX = 100,
      tilesY = 100;
    
    
    ctx.clearRect(0, 0, canvas.width, canvas.height);

Test runner

Ready to run.

Testing in
TestOps/sec
Straightforward
for (var x = 0; x < tilesX; x++) {
  for (var y = 0; y < tilesY; y++) {
    ctx.fillStyle = ((x + y) % 2 === 0) ? 'white' : 'black';
    ctx.fillRect(x * tileWidth, y * tileWidth, tileWidth, tileWidth);
  }
}
ready
Optimized 1
var totalWidth = tilesX * tileWidth,
  totalHeight = tilesY * tileWidth,
  strip = 0,
  doubleWidth = tileWidth * 2;

ctx.fillStyle = 'white';
for (var x = 0, strip = 0; x < totalWidth; x += tileWidth, strip += 1) {
  for (var y = (strip & 2) ? tileWidth : 0; y < totalHeight; y += doubleWidth) {
    ctx.fillRect(x, y, tileWidth, tileWidth);
  }
}

ctx.fillStyle = 'black';
for (var x = 0, strip = 0; x < totalWidth; x += tileWidth, strip += 1) {
  for (var y = (strip % 2) ? 0 : tileWidth; y < totalHeight; y += doubleWidth) {
    ctx.fillRect(x, y, tileWidth, tileWidth);
  }
}
ready
Optimized 2
var totalWidth = tilesX * tileWidth,
  totalHeight = tilesY * tileWidth,
  strip = 0,
  doubleWidth = tileWidth * 2;

ctx.fillStyle = 'white';
for (var x = 0, strip = 0; x < totalWidth; x += tileWidth, strip += 1) {
  for (var y = (strip & 1) ? tileWidth : 0; y < totalHeight; y += doubleWidth) {
    ctx.fillRect(x, y, tileWidth, tileWidth);
  }
}

ctx.fillStyle = 'black';
for (var x = 0, strip = 0; x < totalWidth; x += tileWidth, strip += 1) {
  for (var y = (strip & 1) ? 0 : tileWidth; y < totalHeight; y += doubleWidth) {
    ctx.fillRect(x, y, tileWidth, tileWidth);
  }
}
ready
Optimized 3
var totalWidth = tilesX * tileWidth,
  totalHeight = tilesY * tileWidth,
  strip = 0,
  doubleWidth = tileWidth * 2;

ctx.fillStyle = 'white';
for (var x = 0, strip = 0; x < totalWidth; x += tileWidth, strip += 1) {
  for (var y = (strip % 2) * tileWidth; y < totalHeight; y += doubleWidth) {
    ctx.fillRect(x, y, tileWidth, tileWidth);
  }
}

ctx.fillStyle = 'black';
for (var x = 0, strip = 0; x < totalWidth; x += tileWidth, strip += 1) {
  for (var y = ((strip + 1) % 2) * tileWidth; y < totalHeight; y += doubleWidth) {
    ctx.fillRect(x, y, tileWidth, tileWidth);
  }
}
ready

Revisions

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