From 55991e33af6fece07ea347a059da061b76fc95f5 Mon Sep 17 00:00:00 2001 From: Igor Minar Date: Wed, 4 Jun 2014 07:16:15 -0700 Subject: [PATCH] perf(forEach): cache array length Micro-optimization :-) BREAKING CHANGE: forEach will iterate only over the initial number of items in the array. So if items are added to the array during the iteration, these won't be iterated over during the initial forEach call. This change also makes our forEach behave more like Array#forEach. --- src/Angular.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Angular.js b/src/Angular.js index 0ccb04ba..523b3da3 100644 --- a/src/Angular.js +++ b/src/Angular.js @@ -229,8 +229,9 @@ function isArrayLike(obj) { * @param {Object=} context Object to become context (`this`) for the iterator function. * @returns {Object|Array} Reference to `obj`. */ + function forEach(obj, iterator, context) { - var key; + var key, length; if (obj) { if (isFunction(obj)) { for (key in obj) { @@ -243,8 +244,9 @@ function forEach(obj, iterator, context) { } else if (obj.forEach && obj.forEach !== forEach) { obj.forEach(iterator, context); } else if (isArrayLike(obj)) { - for (key = 0; key < obj.length; key++) + for (key = 0, length = obj.length; key < length; key++) { iterator.call(context, obj[key], key); + } } else { for (key in obj) { if (obj.hasOwnProperty(key)) {