<canvas id="canvas" width="800" height="300"></canvas>
$canvas = document.getElementById('canvas');
$context = $canvas.getContext('2d');
$context.clearRect(0, 0, 800, 300);
$iterations = 500;
for (let i=0; i<$iterations; ++i) {
$context.fillStyle = 'rgba(100,150,200,0.9)';
$context.fillRect(0, 0, 1, 1);
}
for (let i=0; i<$iterations; ++i) {
const context = $canvas.getContext('2d');
context.fillStyle = 'rgba(100,150,200,0.9)';
context.fillRect(0, 0, 1, 1);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using a global context variable | |
Invoking getContext() before every fillRect() |
Test name | Executions per second |
---|---|
Using a global context variable | 1796.8 Ops/sec |
Invoking getContext() before every fillRect() | 1017.4 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Benchmark Purpose
The benchmark tests two different approaches to rendering a small rectangle on a canvas element:
getContext()
before every fillRect() callThe goal is to compare the performance of these two approaches and determine which one is faster.
Options Compared
The two options being compared are:
getContext()
before every fillRect() call, which creates a new context instance on each iteration of the loop.Pros and Cons
Library and Special JS Feature
The benchmark uses the canvas
HTML element, which is a standard part of the web platform. There are no external libraries required.
There are no special JavaScript features or syntax used in this benchmark.
Other Considerations
Alternatives
Other approaches could be used to render a rectangle on a canvas element, such as:
requestAnimationFrame
functionHowever, these alternatives would likely introduce additional complexity and may not provide significant performance benefits over the two options being compared in this benchmark.