<svg version="1.1"
width="300" height="200"
xmlns="http://www.w3.org/2000/svg">
<rect id="rect1" width="100" height="100" fill="red" />
</svg>
var rect = document.getElementById('rect1');
var width = Number(rect.getAttribute('width'));
rect.setAttribute('width', width);
if (rect.getAttribute('width') !== `${width}`) {
alert('this code does not run');
}
if (rect.getAttribute('width') !== `${++width}`) {
rect.setAttribute('width', width);
}
rect.setAttribute('width', ++width);
const cache = width;
if (cache !== width) {
alert('this code does not run');
}
const cache = width;
if (cache !== ++width) {
rect.setAttribute('width', width);
}
if (rect.getAttribute('width') === `${width}`) {
rect.setAttribute('width', width);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
set the same value | |
check and set nothing | |
check and set a new value | |
set a new value | |
check cache and set nothing | |
check cache and set a new value | |
check and set the same value |
Test name | Executions per second |
---|---|
set the same value | 11957576.0 Ops/sec |
check and set nothing | 51463064.0 Ops/sec |
check and set a new value | 1991300.0 Ops/sec |
set a new value | 4642188.0 Ops/sec |
check cache and set nothing | 167591792.0 Ops/sec |
check cache and set a new value | 4640350.0 Ops/sec |
check and set the same value | 7037838.0 Ops/sec |
Let's dive into the benchmark and explore what's being tested, the options compared, pros and cons of each approach, and other considerations.
What is being tested?
The provided benchmark measures the performance difference between various approaches to setting an attribute value on an HTML element. The focus is on comparing three types of operations:
width
attribute with a fixed value using setAttribute
.cache
) and checking if it hasn't changed before updating the attribute.Additionally, there are variations of these approaches:
width
variable and passing it to setAttribute
.width
variable while keeping the initial value in cache
, then checking if it hasn't changed before updating the attribute.width
variable on every iteration, but only when the current value is different from the stored cache.Options compared
The benchmark compares six distinct approaches:
setAttribute('width', width)
if (rect.getAttribute('width') !==
${width}) { ... }
if (cache !== width) { ... }
with const cache = width;
width++
and passing it to setAttribute
if (cache !== ++width) { rect.setAttribute('width', width); }
with const cache = width;
rect.setAttribute(width++)
Pros and cons of each approach
Here's a brief summary:
cache
variablewidth
variable incrementally while checking if it has changed.cache
variableOther considerations
Alternatives
Some alternative approaches could include:
cache
).Keep in mind that these alternatives would likely introduce additional complexity and may not be necessary for the specific use case being benchmarked.