<script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<style>
#container { visibility: hidden; }
</style>
<div id="container">
</div>
var container = $('#container')
var itemCount = 300;
for (var i = 0; i < itemCount; i++) {
container.append('<div>Item ' + i + '</div>');
}
var items = container.children();
items.each(function(index,item) {
var $item = $(item);
$item.on('click', function() { console.log('Item clicked'); });
$item.on('hover', function() { console.log('Item hovered'); });
$item.on('mouseenter', function() { console.log('Item mouseentered'); });
});
items.each(function(index,item) {
var $item = $(item);
$item.off('click');
$item.off('hover');
$item.off('mouseenter');
});
items.each(function(index,item) {
var $item = $(item);
$item.on('click', function() { console.log('Item clicked'); });
});
items.each(function(index,item) {
var $item = $(item);
$item.off('click');
});
items.on('click', function() { console.log('Item clicked'); });
items.off('click');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
.each loop and multiple on-assignenements | |
.each loop and single on-assignement | |
no loop and .on-assignement on list |
Test name | Executions per second |
---|---|
.each loop and multiple on-assignenements | 126.9 Ops/sec |
.each loop and single on-assignement | 345.0 Ops/sec |
no loop and .on-assignement on list | 361.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Overview
MeasureThat.net is a website where users can create and run JavaScript microbenchmarks to compare the performance of different approaches. The provided JSON benchmark definition represents a test case that measures the performance of event listeners on an HTML list.
Benchmark Definition
The benchmark definition consists of two parts:
Individual Test Cases
There are three test cases:
.each
method. It then sets up multiple events (click, hover, and mouseenter) for each item..on
method without iterating over it with .each
. It then removes the event listener.Pros and Cons
Here's a brief overview of the pros and cons for each approach:
Library and Purpose
The provided benchmark uses jQuery as a library. jQuery is a popular JavaScript library that simplifies DOM manipulation, event handling, and other common tasks.
In this specific benchmark, jQuery's .each
method is used to iterate over the list elements, while its .on
method is used to attach events to individual elements or the entire element list.
Special JS Features
There are no special JavaScript features mentioned in the provided benchmark definition.
Alternatives
Other alternatives for event handling and iteration include:
forEach
, map
, filter
) instead of jQuery's .each
element.addEventListener
)Keep in mind that these alternatives may have different performance characteristics or trade-offs compared to the approaches used in the benchmark.