var arr = (new Array(10000)).fill(0).map((x, i) => { return i + 1 })
arr.forEach(val => console.log(val))
Object.keys(arr).forEach(key => console.log(arr[key]))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.forEach | |
Object.keys().forEach |
Test name | Executions per second |
---|---|
Array.forEach | 42.5 Ops/sec |
Object.keys().forEach | 41.2 Ops/sec |
Let's break down the test case and explain what's being tested.
The test case compares two approaches to iterate over an array:
Array.forEach
Object.keys().forEach
What is being tested?
The test is checking which approach is faster for iterating over a large array (in this case, 10,000 elements) and logging each element's value to the console.
Options compared:
Array.forEach
: A method that calls a provided function once for each element in an array, without returning any value.Object.keys().forEach
: A method that calls a provided function once for each key in an object (which is used to iterate over arrays in this case).Pros and cons of each approach:
Array.forEach
:Object.keys()
).Object.keys().forEach
:Object.keys()
.Library and syntax:
Neither approach uses a dedicated library. However, Array.forEach
has been a part of the JavaScript language since ECMAScript 5 (2011), while Object.keys().forEach
is more recent, introduced in ECMAScript 2018 (Arrow Functions).
Special JS feature or syntax:
None are explicitly mentioned.
Other alternatives:
If you need to iterate over an array and want to explore alternative approaches, consider:
for...of
loops, which have been available since ECMAScript 6 (2015).forEach
methods from other libraries, such as Lodash or Ramda.For this specific test case, the two approaches are simple and straightforward. The choice between them ultimately comes down to personal preference, readability considerations, and compatibility with different environments.