In examples below i deal with java.util.List datatype's implementations, but same repeats also in many other, especially imperiative syntax following programming languages, and also in other datatypes like arrays, map's, etc.
We can see often in programming code, and study examples following kind for-loops:
for(int i = 0; i < list.size(); i++) {
doSomething(list.get(i));
}
There isn't anything wrong in example, but if you have interested to write optimized code, recommended way to write for ( foreach ) loop looks following:
for(int i = 0, len = list.size(); i < len; i++) {
doSomething(list.get(i));
}
Upper exammple has a problem that it calls list.size() method before every iteration when variable comparison is done, this can also be wanted if it is known what it do, if like for example the size of the list is changed during iteration, but most commonly this isn't purpose.. for expression first part, which is mainly intended variable initialization, execute only once, and so in comparison the length variable is known, and it is not needed to ask again from list, which executes more processor time.
Well, mostly lists are quite small, and achieved benefit is quite minimal, but on the other hand the other syntax is small change to study, and once it has acquired, it will come straight from spinal and doesnt cause extra headache.
Furthermore list can be someway dynamizally, for example: size() method can execute database query, or something other, where benefit highlighted.