Yes, the termination expression gets evaluated every time. Thus, you are correct that preserving length once may be a small increase in performance. But more importantly, it changes the logic, which can make a difference if myArray gets reassigned.
for (int i = 0; i < myArray.length; i++) { if (something-something-something) { myArray = appendToMyArray(myArray, value);
Now it matters a lot: first save the length of the array in a variable.
Usually you do not see such code with an array. But with an arrayList or other collection, the size of which can increase (or decrease) in the body of the loop, it makes the difference big if you calculate the size once or every time. This idiom appears in algorithms where you save a to-do list. For example, here is a partial search algorithm for everyone who is directly or indirectly associated with someone:
ArrayList<Person> listToCheck = new ArrayList<>(KevinBacon); for (int i = 0; i < listToCheck.size(); i++) { List<Person> connections = allConnections(listToCheck.get(i)); for (Person p : connections) { if ([p has not already been checked]) { listToCheck.add(p);
source share