K''
K''

Reputation: 5238

different between loop termination assignments

what is the difference between the following 2 loops

for(int i = 0, n = array.length; i < n; i++)
    //do something

for(int i = 0; i < array.length; i++)
    //do something

does the loop calculate the array length each iteration in the second loop?

Upvotes: 0

Views: 55

Answers (2)

DuncanACoulter
DuncanACoulter

Reputation: 2156

This depends entirely on the language and data structure we are dealing with here. It looks like array.length is a member variable and as such it is simply being returned and not calculated but it could be a property and hence could be, but probably isn't, re-calculated each time.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502825

The first form only evaluates the expression array.length once, and remembers it in an extra local variable (n). In most languages I've worked with, finding the length of an array is incredibly quick anyway, so the latter form is preferred.

Upvotes: 3

Related Questions