different between loop termination assignments
what is the difference between the follow开发者_JAVA百科ing 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?
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.
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.
精彩评论