Just came across a neat for loop idiom I don't think I'd ever considered before:
for(long i = 0, m = file.length(); i < m; i++)
As a general rule, it's bad (with varying degrees of badness) to call a function in a loop condition. One of my favorite examples of why is exemplified by this bit of C:
for(n=0; n<strlen(str); n++)
print str[n];
It turns what should be a Theta(n) algorithm into a Theta(n^2) algorithm.
Usually what I'd do in that case is something like (back to Java):
int length = file.length(); // or str.length, etc.
for(int n=0; n<length; n++){...}
But the idiom above allows you to put it in the loop declaration, which allows you to better associate it with the loop conceptually, and has the added benefit of making the variable scoped to the loop.
Feel free to post a comment below. Please see my comment policy.
Formatting Rules (No HTML):