Question About .forEach Usage vs for..of in Babylon.js Source Code

In my own projects, I use linting rules like unicorn/no-array-for-each due to the minor performance cost associated with using .forEach compared to for..of.

While reviewing the Babylon.js source code, specifically in assetContainer.ts, I noticed that .forEach is frequently used for traversing arrays. Is there a specific reason for this choice?

For reference, here is a benchmarking comparison of .forEach vs for..of: https://leanylabs.com/blog/js-forEach-map-reduce-vs-for-for_of/.

I’d love to understand the reasoning behind this design decision. Is it for readability, consistency, or something else?

1 Like

More of an oversight. We should replace the forEach by for..of (To be honest I did not know about the perf difference)

cc @RaananW who is adding more linting to our codebase

3 Likes

You may find this link interesting: GitHub - sindresorhus/eslint-plugin-unicorn: More than 100 powerful ESLint rules

2 Likes

I started fixing it:
Replace forEach by for..of for performance reasons by deltakosh · Pull Request #16513 · BabylonJS/Babylon.js

3 Likes

The only proper, performant way, to iterate an array is a for loop. for…of is (comparably) slow as well. Unsurprisingly, for..in is the slowest :slight_smile: . Try this - for vs forEach (v617)

There are a few (better yet - a LOT) of eslint flags I want to turn on, and I am planning on discussing this internally with the team and then publish them here for transparency and review. This is 100% one of them.

Having said that - forEach and for…of are, IMO, perfectly fine when not in the hot path. The code is more readable, doesn’t require references from the array, and has some other advantages (for example - context in a forEach loop).

3 Likes