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.
This commit is contained in:
Igor Minar
2014-06-04 07:16:15 -07:00
committed by rodyhaddad
parent 8c6a8171f9
commit 55991e33af

View File

@@ -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)) {