<div id="test"></div>
const testEl = document.getElementById('test');
var a = {
get testRect() {
return testEl.getBoundingClientRect();
},
set testRect(val) {
}
}
let rectData = a.testRect;
let height = a.testRect.height;
let width = a.testRect.width;
let rectData = a.testRect;
let height = rectData.height;
let width = rectData.width;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
No caсh | |
Caсhing |
Test name | Executions per second |
---|---|
No caсh | 49019.0 Ops/sec |
Caсhing | 146903.7 Ops/sec |
The provided benchmark evaluates the performance of accessing an element's dimensions using the getBoundingClientRect()
method in two different ways: without caching the result and with caching the result. The goal is to determine which approach offers better performance in terms of execution speed.
No Cache Test:
let rectData = a.testRect;
let height = a.testRect.height;
let width = a.testRect.width;
a.testRect
is called three times to access the element's dimensions. Each call to a.testRect
invokes the getter for testRect
, which calls getBoundingClientRect()
anew every time, retrieving the fresh dimensions from the browser's rendering engine.Cache Test:
let rectData = a.testRect;
let height = rectData.height;
let width = rectData.width;
a.testRect
is called only once, and its returned value is stored in rectData
. The height and width are then accessed from rectData
, which is a cached version of the dimensions, reducing the number of calls to getBoundingClientRect()
.Pros:
Cons:
Pros:
rectData
, the test reduces the total number of calls to getBoundingClientRect()
, thus speeding up the retrieval of the height and width.Cons:
Rendering Frequency: In practice, the performance difference could become negligible if the dimensions of the element change frequently due to layout shifts or animations. Caching is most beneficial in scenarios where element dimensions remain stable throughout the operations.
Browser Variability: Results may vary across different browsers and devices, as rendering engines handle DOM access differently. The benchmark shows results specifically for Chrome on a Linux desktop.
Real-world Applications: This principle of caching can be extended to many other operations, such as API calls, DOM manipulations, and computations that require multiple references to the same data.
Other alternatives for improving access speed could include:
offsetHeight
/offsetWidth
, or even custom caching strategies that update when necessary, could be implemented.In conclusion, the caching approach significantly improves performance when fetching dimensions of elements in JavaScript and demonstrates broader principles applicable in various performance-sensitive programming contexts.