<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js'></script>
<div class="grand">
<div class="parent"> Awesome stuff! </div>
<div class="my-class">
<p> I like carrots! </p>
</div>
</div> <div class="grand">
<div class="parent"> Awesome stuff! </div>
<div class="my-class">
<p> I like carrots! </p>
</div>
</div>
<div class="grand">
<div class="parent"> Awesome stuff! </div>
<div class="my-class">
<p> I like carrots! </p>
</div>
</div>
<div class="grand">
<div class="parent"> Awesome stuff! </div>
<div class="my-class">
<p> I like carrots! </p>
</div>
</div>
<div class="grand">
<div class="parent"> Awesome stuff! </div>
<div class="my-class">
<p> I like carrots! </p>
</div>
</div>
<div class="grand">
<div class="parent"> Awesome stuff! </div>
<div class="my-class">
<p> I like carrots! </p>
</div>
</div>
$('*').last().css("background-color", "#cccccc"); //case-1
$('div').last().css("background-color", "#cccccc"); //case-2
$('*').last().css("background-color", "#cccccc");
$('div').last().css("background-color", "#cccccc");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
a | |
b |
Test name | Executions per second |
---|---|
a | 64243.2 Ops/sec |
b | 119961.2 Ops/sec |
I'll break down the provided JSON and explain what's being tested, compared, and other considerations.
Benchmark Definition
The benchmark definition represents a single test case, which is to measure the performance of two different approaches:
$('*').last().css('background-color', '#cccccc');
$('div').last().css('background-color', '#cccccc');
These two expressions are used to select the last element in the HTML document and set its background color.
Comparison
The two expressions differ in how they select elements:
$('*')
selects all elements on the page, and .last()
returns the last element among them.$('div')
selects only elements with the div
tag name, and .last()
returns the last one found.Options Compared
The two options are compared in terms of:
Pros and Cons
$('*')
last() approach:$('div')
last() approach:div
elements only, might be faster for a single element.div
elements with the same class or ID.Library and Purpose
The jQuery library is used in both expressions. jQuery provides a convenient way to select and manipulate elements on the page, making it easier to write dynamic code.
Special JS Feature/Syntax
There doesn't appear to be any special JavaScript features or syntax being tested here.
Other Alternatives
If you were to rewrite this benchmark without using jQuery, you might consider using more modern JavaScript DOM manipulation APIs, such as document.body.lastElementChild
or HTMLElements[0]
. However, these alternatives would likely have similar performance characteristics to the two expressions being compared.
Keep in mind that this benchmark is designed to test the performance of a specific code path, and the results might not be representative of real-world usage.