<canvas id="c" width="800" height="600"></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<1000000; ++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=500;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 | 478.2 Ops/sec |
fillRect/join | 418.2 Ops/sec |
1×1 Image Data | 63.3 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
What is being tested?
On MeasurThat.net, users can create and run JavaScript microbenchmarks to compare the performance of different approaches in various scenarios. In this case, we're looking at three individual test cases for a specific benchmark: "Setting Canvas Pixel with 1M iterations".
The goal of this benchmark is to measure the performance of different ways to set pixel values on an HTML canvas element.
Test options and their pros/cons
There are three test options:
fillRect
with concatenation ("fillRect/concat"
)$ctx.fillStyle = 'rgba(' + px.r + ',' + px.g + ',' + px.b + ',' + (px.a / 255) + ')';
$ctx.fillRect(px.x, px.y, 1, 1);
Pros:
Cons:
fillRect
with array join ("fillRect/join"
)$ctx.fillStyle = 'rgba(' + [px.r, px.g, px.b, px.a/255].join() + ')';
$ctx.fillRect(px.x, px.y, 1, 1);
Pros:
Cons:
putImageData
with pixel data manipulation ("1×1 Image Data"
)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);
Pros:
fillRect
methods.Cons:
Library usage:
In this benchmark, two libraries are used:
Special JS features or syntax:
There are no special JavaScript features or syntax mentioned in this benchmark. The code is written in standard JavaScript and relies on the Canvas API for its functionality.
Alternatives:
For measuring performance, MeasurThat.net provides alternatives to the fillRect
methods:
Keep in mind that the performance results may vary depending on the specific use case, hardware, and software configuration.