<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js'></script>
var arr = {aa: 12, bb: 33, cc:44, dd: 4444};
var temp;
$.each(arr, function(key, val) {
temp = val;
});
var temp;
Object.keys(arr).forEach(function(key) {
temp = this;
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
jQuery.each | |
Array.prototype.forEach |
Test name | Executions per second |
---|---|
jQuery.each | 1796474.8 Ops/sec |
Array.prototype.forEach | 1720761.0 Ops/sec |
Let's break down the provided benchmark definition and test cases to understand what is being tested.
Benchmark Definition
The benchmark measures the performance of two approaches for iterating over an array:
$.each(arr, function(key, val) { ... });
- This uses jQuery's $.each()
method.Object.keys(arr).forEach(function(key) { ... });
- This uses the Array.prototype.forEach()
method.Script Preparation Code
The script preparation code creates an array arr
with four elements: aa
, bb
, cc
, and dd
.
Html Preparation Code
The HTML preparation code includes a reference to jQuery version 3.3.1, which is used by the benchmark.
Test Cases
There are two test cases:
$.each()
method from jQuery to iterate over the array. The script prepares a temporary variable temp
and assigns it the value of each element in the array.forEach()
method on the Object.keys()
result of the array, which returns an array of keys. The script prepares a temporary variable temp
and assigns it the value of the current key (which is actually a string representation of the index).Library
In both test cases, jQuery's $.each()
method is used as a reference implementation for iteration.
Special JavaScript Feature or Syntax
There are no special features or syntaxes used in this benchmark.
Pros and Cons
Here are some pros and cons of each approach:
Array.prototype.forEach()
: Pros:Other Alternatives
Some other alternatives for iterating over arrays in JavaScript include:
for...of
loop: A modern and concise way to iterate over arrays using a for...of
loop.map()
, filter()
, and reduce()
methods: While not as straightforward as forEach()
, these methods can be used for more complex operations on array elements.In the context of this benchmark, the use of $.each()
versus Array.prototype.forEach()
is primarily a matter of syntax choice and familiarity. The test results will likely show that Array.prototype.forEach()
outperforms $.each()
due to its native implementation in JavaScript.