<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js'></script>
var arr = Array(1000).fill().map(() => Math.floor(100 * Math.random()));
arr.forEach(item => { });
$.each(arr, item => { });
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Native foreach | |
jQuery each |
Test name | Executions per second |
---|---|
Native foreach | 456411.0 Ops/sec |
jQuery each | 340620.4 Ops/sec |
Let's break down the provided JSON and explain what's being tested, compared, and the pros/cons of different approaches.
Benchmark Definition
The benchmark is comparing two JavaScript methods: forEach
(native) and $.each
(jQuery). The goal is to measure which one performs better in terms of execution speed on a given dataset.
Script Preparation Code
The script preparation code creates an array of 1000 random numbers using the Array
constructor, fill()
, and map()
methods:
var arr = Array(1000).fill().map(() => Math.floor(100 * Math.random()));
This code is executed before running the benchmark.
Html Preparation Code
The HTML preparation code includes a script tag that loads the jQuery library from a CDN:
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js'></script>
This code is executed before running the benchmark as well.
Individual Test Cases
There are two test cases:
forEach
: This test case runs the native JavaScript forEach
method on the prepared array:arr.forEach(item => { });
.each()
: This test case runs the jQuery .each()
method on the prepared array, which is essentially equivalent to using a traditional for
loop:$.each(arr, item => { });
Benchmark Results
The benchmark results show two browsers (Firefox 121) running the same test cases. The "Native forEach
" test case has an execution speed of approximately 456,411 executions per second, while the ".jQuery .each()
" test case has a slower execution speed of around 340,620 executions per second.
Pros and Cons
Here are some pros and cons of each approach:
forEach
:.each()
:Library - jQuery
The $.each
method is part of the jQuery library, which provides a set of DOM manipulation and event handling APIs. In this benchmark, jQuery is used as a library to provide an alternative iteration mechanism.
Note that in modern JavaScript environments, you can use other libraries like Lodash or Ramda for iteration purposes, but they are not mentioned here.
Special JS Feature - None
There are no special JS features or syntax used in these test cases. The focus is on the fundamental performance comparison between native forEach
and jQuery .each()
.
Other Alternatives
Other alternatives to iterate over arrays in JavaScript include:
for
loopsmap()
, filter()
, and reduce()
These alternatives may offer different trade-offs between performance, readability, and maintainability.