You'd have to define "really big," and you'd have to test it with your representative data, but the short answer is yes, it's more overhead to use forEach
than direct property access, for a couple of reasons:
Modern JavaScript engines are pretty smart about objects and can optimize direct property access quite well.
To use forEach
, you have to make function calls. Function calls are extremely cheap, but they aren't free.
In the course of finding the element in the array, you'll be doing various direct property accesses (human.id
), so right there you're doing the same work you'd've done with direct access, but you're doing it over and over again.
Now, not all objects are equal in terms of property access time. In particular, with a modern engine like V8, if you do something to the object that makes the engine throw away its optimizations and fall back on "dictionary mode" (treating the object like a hash table, instead of doing smarter things), property access on that object will be a lot slower than on one where the optimizations remain in place. One such operation is delete
, which causes V8 to put the object in "dictionary mode." Example on jsperf (Firefox's engine, SpiderMonkey, bizarrely shows an improvement with the object delete
was used on; perhaps it's so fast it's a measurement error, but I ran it several times with consistent results...)
So in theory, if you had a small number of entries in your array, and you built up the array in a way that let the engine optimize it as a true array behind-the-scenes, and the object you would have used instead would have been in "dictionary mode," maybe you might find a use case where forEach
was faster. It doesn't seem likely, but it's remotely possible.