theJava
theJava

Reputation: 15044

Difference between these two for loops

for (var ctr = arr.length - 1; ctr >= 0; ctr--) {

}

for (var ctr = 0; ctr < arr.length; ctr++) {

}
  1. Does both of them does the same job or the first one does things differently.
  2. Which is the best way to perform compared to the above two.

Upvotes: 2

Views: 89

Answers (5)

Quentin
Quentin

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

Amar Palsapure
Amar Palsapure

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

Anthony Grist
Anthony Grist

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

Timofey
Timofey

Reputation: 2518

The two loops are different in the direction of an array traversal:

  1. starts from the last element and finishes in the first element
  2. vice versa, starts from the fist element and finishes in the last one

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

Andreas Eriksson
Andreas Eriksson

Reputation: 9027

The first one loops through the array in reverse. The second one in the order the elements appear.

Upvotes: 0

Related Questions