<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 class="about-shop">Hello azula</h1>
</body>
</html>
const cache = {};
function $(selector) {
if (cache[selector] !== undefined) {
console.count("cached");
return cache[selector];
}
const cached = document.querySelector(selector);
cache[selector] = cached;
return cached
};
const selector1 = document.querySelector(".about-shop");
const selector2 = document.querySelector(".about-shop");
const selector3 = document.querySelector(".about-shop");
const selector1 = $(".about-shop");
const selector2 = $(".about-shop");
const selector3 = $(".about-shop");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
querySelector | |
querySelector + cache |
Test name | Executions per second |
---|---|
querySelector | 4996746.5 Ops/sec |
querySelector + cache | 90174.0 Ops/sec |
Benchmark Overview
The provided benchmark compares the performance of two approaches to selecting an HTML element using JavaScript: document.querySelector()
and a custom implementation called $()
. The goal is to determine which approach is faster.
Script Preparation Code
The script preparation code defines a custom function $()
that wraps around document.querySelector()
. It introduces caching, where if the same selector is used multiple times, the cached result is returned instead of recalculating it. This approach aims to reduce the number of DOM queries.
const cache = {};
function $(selector) {
if (cache[selector] !== undefined) {
console.count("cached");
return cache[selector];
}
const cached = document.querySelector(selector);
cache[selector] = cached;
return cached;
}
Pros of caching
Cons of caching
Comparison
The two test cases compare the performance of document.querySelector()
(without caching) versus the custom implementation with caching ($()
). The benchmark measures the number of executions per second for each approach.
Library and Purpose
In this case, there is no explicit library being used. However, it's worth noting that using a more robust caching mechanism or considering libraries like LRU Cache might improve performance in real-world scenarios.
Special JS feature or syntax
There are two special JavaScript features being used:
$(selector)
function uses template literals (e.g., "."
) to create a string from the variable.cache[selector]
) uses object property access to store and retrieve values.Alternatives
If you need to improve performance in similar scenarios, consider the following alternatives:
document.querySelector()
repeatedly, use these APIs to schedule DOM queries at optimal times.Keep in mind that the choice of approach depends on your specific requirements, performance constraints, and use case complexity.