Permalink
Browse files

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.
  • Loading branch information...
IgorMinar authored and rodyhaddad committed Jun 4, 2014
1 parent 8c6a817 commit 55991e33af6fece07ea347a059da061b76fc95f5
Showing with 4 additions and 2 deletions.
  1. +4 −2 src/Angular.js
View
@@ -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++) {

This comment has been minimized.

Show comment
Hide comment
@chinchang

chinchang Jun 29, 2014

@IgorMinar Shouldn't this native for loop be used always for arrays as they are faster than forEach? The above else if condition gets hit for arrays, thus running the slower forEach loop. http://jsperf.com/fast-array-foreach

@chinchang

chinchang Jun 29, 2014

@IgorMinar Shouldn't this native for loop be used always for arrays as they are faster than forEach? The above else if condition gets hit for arrays, thus running the slower forEach loop. http://jsperf.com/fast-array-foreach

This comment has been minimized.

Show comment
Hide comment
@IgorMinar

IgorMinar Jun 30, 2014

Member
@IgorMinar

IgorMinar via email Jun 30, 2014

Member

This comment has been minimized.

Show comment
Hide comment
@chinchang

chinchang Jun 30, 2014

Awesome. Thanks.

@chinchang

chinchang Jun 30, 2014

Awesome. Thanks.

iterator.call(context, obj[key], key);
}
} else {
for (key in obj) {
if (obj.hasOwnProperty(key)) {

1 comment on commit 55991e3

@t0mtaylor

This comment has been minimized.

Show comment
Hide comment
@t0mtaylor

t0mtaylor Sep 3, 2014

This looks familiar :)

This looks familiar :)

Please sign in to comment.