<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 class="about-shop">Hello azula</h1>
</body>
</html>
const cache = new Map();
function $(selector) {
if (cache.has(selector)) {
return cache.get(selector);
}
let cached = document.querySelector(selector);
cache.set(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 with Map |
Test name | Executions per second |
---|---|
querySelector | 657721.9 Ops/sec |
querySelector + cache with Map | 5329.6 Ops/sec |
Let's break down the provided benchmark definition and test cases.
Tested Options:
document.querySelector()
: This is a standard method in JavaScript for selecting an element by its CSS selector.$(selector)
: This is a custom function that wraps around the document.querySelector()
method, introducing caching using a Map
data structure.Pros and Cons of Different Approaches:
document.querySelector()
:$(selector)
with caching using Map
:Map
.Library and Purpose:
Map
: A built-in JavaScript data structure that stores key-value pairs. In this case, it's used as a cache to store the results of previous DOM searches.Special JS Features or Syntax:
None mentioned in the provided benchmark definition.
Other Considerations:
document.querySelector()
may vary depending on the specific use case and requirements.Alternatives:
document.getElementById()
, document.getElementsByTagName()
, or QuerySelectorAll()
.