<canvas id="c" width="300" height="300"></canvas>
$c = document.getElementById('c');
$ctx = $c.getContext('2d');
$ctx.clearRect(0, 0, 800, 300);
$px = $ctx.createImageData(1, 1);
$pxls = [];
for (var i=0; i<10000; ++i) $pxls.push({
x: Math.random() * 800 << 0,
y: Math.random() * 300 << 0,
r: Math.random() * 255 << 0,
g: Math.random() * 255 << 0,
b: Math.random() * 255 << 0,
a: Math.random() * 128 << 0 + 128
});
$i = 0;
for (var i=5000;i--;){
var px = $pxls[$i++ % 10000];
$ctx.fillStyle = 'rgba(' + px.r + ',' + px.g + ',' + px.b + ',' + (px.a / 255) + ')';
$ctx.fillRect(px.x, px.y, 1, 1);
}
for (var i=500;i--;){
var px = $pxls[$i++ % 10000];
$ctx.fillStyle = 'rgba(' + [px.r,px.g,px.b,px.a/255].join() + ')';
$ctx.fillRect(px.x, px.y, 1, 1);
}
for (var i=500;i--;){
var px=$pxls[$i++ % 10000], d=$px.data;
d[0] = px.r;
d[1] = px.g;
d[2] = px.b;
d[3] = px.a;
$ctx.putImageData($px, px.x, px.y);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
fillRect/concat | |
fillRect/join | |
1×1 Image Data |
Test name | Executions per second |
---|---|
fillRect/concat | 81.7 Ops/sec |
fillRect/join | 711.1 Ops/sec |
1×1 Image Data | 267.9 Ops/sec |
Let's break down the provided JSON and benchmark.
Benchmark Definition
The benchmark is defined by two pieces of code: Script Preparation Code
and Html Preparation Code
. The first one sets up the canvas element, gets its 2D drawing context, clears it, creates an image data object, and populates it with random pixel values. The second one defines the HTML structure for the canvas element.
Options being compared
There are three individual test cases being compared:
fillRect/concat
: This option uses a comma-separated string to pass color values to setFillStyle()
.fillRect/join
: This option uses an array to pass color values to setFillStyle()
.1×1 Image Data
: This option uses the putImageData()
method to fill the canvas with image data.Pros and Cons of each approach
fillRect/concat
:fillRect/join
:1×1 Image Data
:Library usage
The benchmark uses the OHRP/51.0.2830.40
browser, which is an older version of Opera. It's likely that this browser has specific optimizations or bugs that affect the performance of these test cases.
JavaScript features and syntax
There are no special JavaScript features or syntax being used in these benchmark definitions. They seem to be standard ECMAScript 5/6 code.
Other alternatives
Other ways to fill a canvas element might include:
fillRect()
with multiple arguments (e.g., fillRect(x, y, width, height)
).Keep in mind that these alternatives may have different performance characteristics and might not be as straightforward to implement as the benchmark's code.