<canvas id="c" width="800" 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=500;i--;){
var px = $pxls[$i++ % 10000];
$ctx.fillStyle = `rgba( ${px.r}, ${px.g}, ${px.b})`;
$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 | 1200.2 Ops/sec |
fillRect/join | 989.1 Ops/sec |
1×1 Image Data | 184.8 Ops/sec |
Measuring JavaScript performance is a complex task, and MeasuredThat.net provides a great platform for benchmarking different approaches.
Benchmark Definition
The provided benchmark definition involves creating an image data buffer and then drawing pixels on a canvas using various methods. The script preparation code sets up the necessary variables and context, while the HTML preparation code defines the canvas element with the required width and height.
Here's a breakdown of what's being tested:
$pxls
) with 10,000 entries.fillRect/concat
: Directly concatenates color values to create the fill style string.fillRect/join
: Joins color values using a space separator.1×1 Image Data
: Uses the putImageData
method to draw the image data directly on the canvas.Options Compared
The three options being compared are:
"rgba( ${px.r}, ${px.g}, ${px.b})"
) to create the fill style string."[px.r,px.g,px.b,px.a/255].join()"
) to create the fill style string.putImageData
: This approach uses the putImageData
method to draw the image data directly on the canvas.Pros and Cons of Each Approach
Here's a brief summary:
putImageData
:Library Used
The benchmark uses the HTML5 Canvas API, which is a built-in library in most modern browsers. The putImageData
method is a part of this API.
Special JavaScript Feature/ Syntax
This benchmark does not use any special JavaScript features or syntax beyond standard ES6 features.
Other Alternatives
If you want to explore alternative approaches for similar benchmarks, consider the following:
Keep in mind that each approach has its strengths and weaknesses, and choosing the best one depends on the specific requirements and constraints of your project.