<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<style>
.dom-user {
color: blue;
}
.dom-suffix {
color: red;
}
.dom-img {
height: 16px;
width: 16px;
}
.css-user {
color: blue;
}
.css-user[suffix]:after {
color: green;
content: attr(suffix);
}
.css-user[img]:before {
content: attr(img, url);
}
</style>
<div id='list'></div>
var users = [];
for (var i = 0; i < 10; ++i) {
users.push({
'username': 'user ' + i,
'img': 'https://www.google.com/images/branding/product/ico/googleg_lodp.ico',
'suffix': '(' + i + ')'
});
}
var list = $("#list");
list.empty();
for (let user of users) {
list.append($(`<span class='dom-user'>${user.username}</span><span class='dom-suffix'>${user.suffix}</span>`));
}
list.empty();
for (let user of users) {
list.append($(`<span class='dom-user'>${user.username}</span>`))
list.append($(`<span class='dom-suffix'>${user.suffix}</span>`));
}
list.empty();
for (let user of users) {
list.append($(`<span class='css-user' suffix='${user.suffix}'>${user.username}</span>`));
}
list.empty();
for (let user of users) {
list.append($(`<span class='css-user' img='${user.img}' suffix='${user.suffix}'>${user.username}</span>`));
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
dom text suffix | |
dom text suffix two parts | |
css text suffix | |
css text img suffix |
Test name | Executions per second |
---|---|
dom text suffix | 1782.0 Ops/sec |
dom text suffix two parts | 1028.8 Ops/sec |
css text suffix | 2053.6 Ops/sec |
css text img suffix | 1990.1 Ops/sec |
Let's dive into the provided benchmark definition and explanations.
Benchmark Definition:
The provided benchmark is designed to compare the performance of different approaches for building dynamic lists of DOM elements with varying levels of complexity. Specifically, it compares four scenarios:
:before
and :after
) with content.Options Compared:
The benchmark tests the performance of the following options:
:before
and :after
pseudo-elements to add content to a single element.Pros and Cons of Each Approach:
Library Used:
The benchmark uses jQuery as the library for DOM manipulation. Specifically, it utilizes append()
and $()
functions to create and manage DOM elements.
Special JS Feature or Syntax:
The benchmark utilizes CSS pseudo-elements (:before
and :after
) with content, which is a standard feature in modern browsers. Additionally, it uses attribute manipulation (e.g., attr(suffix)
) to access attributes on the DOM element.
Alternatives:
If you're interested in exploring alternative approaches or libraries, consider the following:
document.createElement
, appendChild
, etc.) instead of jQuery.Keep in mind that the choice of approach depends on your specific use case, performance requirements, and personal preference.