<canvas height="500" width="500"></canvas>
<canvas height="500" width="500"></canvas>
var [canvas1, canvas2] = Array.from(document.querySelectorAll('canvas'));
var ctx1 = canvas1.getContext('2d')
var ctx2 = canvas2.getContext('2d')
var rects = new Array(100).fill(null).map(() => ({
x: Math.floor(Math.random() * 100),
y: Math.floor(Math.random() * 100),
width: Math.floor(Math.random() * 100) + 1,
height: Math.floor(Math.random() * 100) + 1
}))
for (var rect of rects) {
var cached = document.createElement('canvas')
cached.width = rect.width
cached.height = rect.height
rect.cached = cached.getContext('2d')
rect.cached.fillStyle = 'blue'
rect.cached.fillRect(0, 0, rect.width, rect.height)
ctx1.drawImage(rect.cached.canvas, rect.x, rect.y, rect.width, rect.height)
}
ctx1.clearRect(0, 0, 500, 500)
for (var rect of rects) {
ctx1.drawImage(rect.cached.canvas, rect.x, rect.y, rect.width, rect.height)
}
for (var rect of rects) {
rect.path = new Path2D()
rect.path.rect(rect.x, rect.y, rect.width, rect.height)
ctx2.fillStyle = rect.fill
ctx2.fill(rect.path)
}
ctx2.clearRect(0, 0, 500, 500)
for (var rect of rects) {
ctx2.fillStyle = 'red'
ctx2.fill(rect.path)
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Cached canvas | |
Cached Path2D |
Test name | Executions per second |
---|---|
Cached canvas | 201.3 Ops/sec |
Cached Path2D | 1711.3 Ops/sec |
What is being tested?
The provided JSON represents two benchmark test cases for measuring the performance of two different approaches: using cached canvas context and using Path2D.
Options compared:
Two options are being compared:
canvas
element, creates a 2D drawing context (ctx
) on that canvas, and then draws rectangles from an array onto the canvas.Path2D
API to define a path for each rectangle in the array, which is then filled with a fill color.Pros and Cons of each approach:
Cached Canvas:
Pros:
Cons:
Cached Path2D:
Pros:
Cons:
Path2D
API's complexity.Other considerations:
Array.from(document.querySelectorAll('canvas'))
suggests that this benchmark is designed to test performance in a real-world scenario, where multiple canvas elements may be present.FreeBSD
as an operating system and rv:97.0
as the Firefox version indicates that this benchmark may be targeting specific hardware configurations or versions.Library and its purpose:
The Path2D
API is a part of the HTML5 standard, introduced in 2011. Its primary purpose is to allow for more efficient rendering of complex paths by breaking them down into individual path commands. In this benchmark, it's used to define a path for each rectangle in the array.
Special JS feature or syntax:
None mentioned in the provided code snippets.
Alternative approaches:
Other possible approaches that could be compared in this benchmark include:
Keep in mind that the specific alternatives will depend on the goals and requirements of the benchmark.