<canvas id="c" width="800" height="800"></canvas>
$c = document.getElementById('c');
$ctx = $c.getContext('2d');
$ctx.clearRect(0, 0, 800, 800);
$px = $ctx.createImageData(1, 1);
$pxls = [];
for (var i=0; i<10000; ++i) $pxls.push({
x: Math.random() * 800 << 0,
y: Math.random() * 800 << 0,
r: 250 << 0,
g: 0 << 0,
b: 0,
a: 1
});
$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 | 1088.8 Ops/sec |
fillRect/join | 891.7 Ops/sec |
1×1 Image Data | 98.8 Ops/sec |
Let's dive into explaining the benchmark.
What is tested:
The provided JSON represents a JavaScript microbenchmark that tests the performance of different approaches to filling a canvas pixel with an image data object. The benchmark creates a canvas element, sets up a 2D drawing context, and then fills the pixel with an image data object using three different methods:
rgba
color string.join()
method to concatenate the color components into a single string.Options compared:
The benchmark compares the performance of these three approaches, which provides insight into the optimization techniques used by different browsers and engines.
Pros and Cons:
Library usage:
None of the benchmark scripts explicitly use any external libraries. However, some features might rely on browser-specific APIs or engine optimizations that are not explicitly mentioned in the provided JSON.
Special JS feature or syntax:
<< 0
syntax is used to perform a left shift operation, which is equivalent to multiplying by 2^16 (65536). This is likely used for precision and data type optimization.$pxls[$i++ % 10000]
syntax uses the variable $pxls
, which is an array containing image data objects. The % 10000
part ensures that the index wraps around to the beginning of the array after reaching the end, allowing for a large number of iterations.Alternatives:
To compare the performance of these approaches, one could create more benchmark scripts using different methods, such as:
rgba()
function instead of string concatenation or join method.Keep in mind that the choice of approach will depend on the specific use case, performance requirements, and personal preference.