The "classic" for loop
for (let index = 0; index < array.length; index++) {
const element = array[index]
}
Benchmarks say this is the fastest way and there is no relevant difference in variants like var index
or const n = array.lenght ... index < n
or ++index
.
Fastest way to iterate an object is using keys from Object.key
const keys = Object.keys(object)
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
const value = object[key]
}
Facts seen running tests
for in
is always the slowest way to iterate an array (and also may introduce prototype pollution vulnerability).for in
is good to iterate an object but it also introduces prototype pollution vulnerability, and it is a way slower than using Object.keys
.while
loop is excluded on purpose.Array and Object
var index
is generally slightly faster than let index
, but let index
is a little bit faster with large arrays. To see in stage 2.14
(current LTS), 12
and 15
have the same kind of performance (although 12
is slower).var
or let
affects performance?
++i
affects performance?
node bench array1
# will take ~5h
node report array1
node bench array2
# will take ~4h
node report array2
node bench object
# will take ~1h
node report object
run single test
# node iterate [subject] [size] [type] [#run]
node iterate array1 100 STRING 01
subject: array1|array2|object
size: 10|100|1000|10000|100000|1000000
type: STRING|NUMBER|DATE|OBJECT|MIX
run: free label