Skip to content

Instantly share code, notes, and snippets.

@jsumners
Created October 3, 2025 17:15
Show Gist options
  • Select an option

  • Save jsumners/6dd02d84dfe63fe950eb1e5c2d718243 to your computer and use it in GitHub Desktop.

Select an option

Save jsumners/6dd02d84dfe63fe950eb1e5c2d718243 to your computer and use it in GitHub Desktop.
Testing forEach vs traditional for loops
'use strict'
const assert = require('node:assert')
// node --allow-natives-syntax index.js
const { Suite } = require('bench-node')
const suite = new Suite()
const data = Array.from('a'.repeat(125_000))
suite.add('forEach', () => {
data.forEach(d => { assert.ok(d) })
})
suite.add('for...of', () => {
for (const d of data) {
assert.ok(d)
}
})
// Enabling the for...in test causes the for...of test to perform way
// better.
/*
suite.add('for...in', () => {
for (const d in data) {
assert.ok(d)
}
})
*/
suite.add('for(;;)', () => {
for (let i = 0; i < data.length; i += 1) {
assert.ok(data[i])
}
})
suite.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment