Reputation: 15044
for (var ctr = arr.length - 1; ctr >= 0; ctr--) {
}
for (var ctr = 0; ctr < arr.length; ctr++) {
}
Upvotes: 2
Views: 89
Reputation: 944548
The first loops backwards. The second loops forwards.
The first will have better performance (because the second has to access the arr.length
each time it goes around the loop), but not significantly so unless you are dealing with a lot of objects or looping over them many times.
You can get a similar performance boost with:
for (var i = 0, j = arr.length; i < j; i++) {
}
Upvotes: 0
Reputation: 9680
First one will start from bottom of array and will reach top. Second one will start from top to bottom of array.
If your array has { 3, 2, 1 } and you print this in first loop, it will print 1, 2, 3 and in second loop it will print 3, 2, 1.
Found this http://oreilly.com/server-administration/excerpts/even-faster-websites/writing-efficient-javascript.html which tells about improving performance of javascript. According to it
Another simple way to improve the performance of a loop is to decrement the iterator toward 0 rather than incrementing toward the total length. Making this simple change can result in savings of up to 50% off the original execution time, depending on the complexity of each iteration.
So first one will give better performance.
Hope this helps you.
Upvotes: 4
Reputation: 38345
They both iterate over the contents of an array, but they do it in opposite directions. The first starts from the last element of the array, and works backwards to the first element; the second starts from the first element, and works forwards to the last.
In most cases, they'll provide the same results. However, it's a common practice when you're going to be removing elements from an array to iterate backwards (the first code sample), as any changes to the indices after removing an element will only affect the elements that have already been examined.
Upvotes: 0
Reputation: 2518
The two loops are different in the direction of an array traversal:
Which is the best, depends on your needs.
Consider, for example, the task of finding the first/last occurrence of a character in an array.
Upvotes: 0
Reputation: 9027
The first one loops through the array in reverse. The second one in the order the elements appear.
Upvotes: 0