3 ms·
Is a plain for loop with a counter significantly faster than a forEach? With Object.keys I've been enjoying the simplicity of statements like Object.keys(obj
by kipple 12y ago
Is a plain for loop with a counter significantly faster than a forEach? With Object.keys I've been enjoying the simplicity of statements like
Object.keys(obj).forEach(function (key) {
console.log(obj[key]);
});
but does that hamstring my performance?
- bzbarsky 12y agoYour mileage will vary depending on the browser. If you really care (as in profiling identified this as a hotspot) you should measure the alternatives you're considering. But note that in your specific case chances are the cost of a bunch of console.log() calls completely swamps the cost of either a for loop or a forEach call. console.log() has _incredibly_ complicated behavior.
- ekmartin 12y agoA native counter for-loop will always be faster: http://jsperf.com/angular-foreach-vs-native-for-loop/13 http://jsperf.com/angular-foreach-vs-native-for-loop/13