<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 + ',' + (px.a / 255) + ')';
$ctx.fillRect(px.x, px.y, 1, 1);
}
const alphmult = 1 / 255
for (let i=500;--i;){
const px = $pxls[++$i % 10000];
$ctx.fillStyle = `rgba(${px.r},${px.g},${px.b},${px.a * alphmult})`;
$ctx.fillRect(px.x, px.y, 1, 1);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
fillRect/concat | |
fillRect/optimized further |
Test name | Executions per second |
---|---|
fillRect/concat | 785.5 Ops/sec |
fillRect/optimized further | 794.3 Ops/sec |
Let's break down the provided benchmark definition and test cases.
Benchmark Definition
The benchmark measures the performance of two approaches for filling rectangles on a canvas element:
fillRect/concat
: This approach concatenates the RGB and alpha values in a string, followed by calling fillRect
with the resulting string as the fill style.fillRect/optimized further
: This approach uses a lookup table to optimize the calculation of the fill style string.Options Compared
The two approaches are compared in terms of performance:
ExecutionsPerSecond
).Pros and Cons
fillRect/concat
:fillRect/optimized further
:Library Used
The benchmark uses the Canvas
API, which is a part of the HTML5 specification. The library used is built-in to most modern browsers, making it easily accessible and widely supported.
Special JS Feature or Syntax
The benchmark uses JavaScript features such as:
for...in
loop (used in the fillRect/concat
approach).const alphmult = 1 / 255\r\nfor (let i=500;--i;){\r\nconst px = $pxls[++$i % 10000];\r\n$ctx.fillStyle =
rgba(${px.r},${px.g},${px.b},${px.a * alphmult});\r\n}
) (used in the fillRect/optimized further
approach).Other Considerations
When running this benchmark, it's essential to note that:
Canvas
API is designed for 2D graphics rendering and may not be optimized for every possible use case.Alternative Benchmarking Scenarios
Other alternatives to this benchmark could include:
drawImage
or putImageData
.By considering these alternatives, you can gain a better understanding of your specific use case and choose the most relevant benchmarking approach.