In my opinion, you should avoid micro-optimizations like these. They cost a lot of brain cycles, but most of the time have little impact.
Your application probably has a few central data structures. Those are the ones you should be worried about. For example, if you fill them preallocate them with a good estimate of the size, to avoid repeated resizing of the underlying structure. This especially applies to StringBuffer
, ArrayList
, HashMap
and the like. Design your access to those structures well, so you don't have to copy a lot.
Use the proper algorithms to access the data structures. At the lowest level, like the loop you mentioned, use Iterator
s, or at least avoid calling .size()
all the time. (Yes, you're asking the list every time around for it's size, which most of the time doesn't change.) BTW, I've often seen a similar mistake with Map
s. People iterate over the keySet()
and get
each value, instead of just iterating over the entrySet()
in the first place. The memory manager will thank you for the extra CPU cycles.