First at all, true Objects
don't have a native .map()
method, neither a .length
property. So we are either talking about Arrays
or Array-like-objects
(jQuery objects for instance).
However, there is not faster way to iterate than using a native for
, while
or do-while
loop. All other functional operations do performan (guess what) a function for each iteration which costs.
jQuerys 's .each()
will just performan a for-in
loop when an object is passed to it. That is fairly the fastest way to loop over an object. You could just use a for-in
yourself and you save the overhead call.
Another "good" way in terms of readabilty is to make usage of ES5 features like .keys()
and .map()
. For instance:
var myObj = {
foo: 'bar',
base: 'ball',
answer: 42,
illuminati: 23
};
Object.keys( myObj ).map(function( prop ) {
console.log( myObj[ prop ] );
});
Which I think is a very good tradeof in terms of readabilty, convinience and performance. Of course you should use an ES5 abstraction library for old'ish browser.
But again, no way to beat native loops in terms of performance.