Created
October 3, 2025 17:15
-
-
Save jsumners/6dd02d84dfe63fe950eb1e5c2d718243 to your computer and use it in GitHub Desktop.
Testing forEach vs traditional for loops
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| '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