Why are iterators significantly slower than indexed access?

39 views
Skip to first unread message

Avin Kavish

unread,
Aug 18, 2022, 10:31:53 AM8/18/22
to v8-dev
Hello,

Not sure if I should be asking on the node.js repo, thought since it was a built in, must be related here. Array iteration using it's iterator seems to be about 17% slower than indexed access. Not sure if it's to do with this particular benchmark, I used an array with 10k elements. Here's my source code,

import b from 'benny'

const testData = Array.from({ length: 10_000 }, () => new Object())

let x, y, z

b.suite(
'iteration',
b.add('for i', () => {
  for (let i = 0; i < testData.length; i++) {
    x = testData[i]
   }
}),

b.add('for of', () => {
  for (let testDatum of testData) {
    y = testDatum
  }
}),

b.add('for each', () => {
  testData.forEach((value, index) => {
    z = value
  })
}),

b.cycle(),
b.complete(),
b.save({ file: 'array-iteration', version: '1.0.0' }),
b.save({ file: 'array-iteration', format: 'chart.html' }),
)

Avin Kavish

unread,
Aug 18, 2022, 10:32:50 AM8/18/22
to v8-dev
On node 16, I got

  for i:
    60 595 ops/s, ±12.74%   | fastest

  for of:
    50 041 ops/s, ±0.22%   | 17.42% slower

  for each:
    35 661 ops/s, ±17.08%   | slowest, 41.15% slower

Jakob Kummerow

unread,
Aug 18, 2022, 11:16:02 AM8/18/22
to v8-dev
Because they do more work: somewhere under the hood they must do the same indexed access, and then they do other stuff in addition to that. Indexed access is the simplest operation, so it runs fastest.

If anything, it's amazing that the differences you measure are so small. All the effort that went into Turbofan over the years is making it pretty good at optimizing stuff away.

Also, keep in mind that it's nearly impossible to draw useful conclusions from such microbenchmarks. With small tweaks to the test setup that "shouldn't" change anything, you'll get very different results; e.g. "for i" and "for of" have identical performance in many scenarios, just not in this one.


--
Reply all
Reply to author
Forward
0 new messages