The efficiency is unlikely to be significant - certainly System.out.println
is much more likely to be the bottleneck in your particular example.
The second approach (enhanced for loop) is the most readable however. Note that the three approaches don't do the same thing - the first one will iterate from the end rather than the start. Getting the right behaviour almost always trumps running a teeny, tiny bit faster. The more readable your code is, the more likely you are to get it right.
Go for readability, measure the performance of your app, and if it becomes a problem, micro-optimise the bottlenecks (continuing to measure at every step).
EDIT: I was basing this answer on the first line of the question, showing an ArrayList<T>
being used.
If you want an answer for any List<T>
then there simply isn't an accurate answer. List<T>
doesn't offer any guarantees about complexity. It doesn't say how fast you should expect get
to be, nor how fast you should expect an iterator to be. You could be using an implementation which has good random access, but a painfully slow iterator. It's unlikely, but it would still be a valid List<T>
.
In short: if you're concerned about the efficiency, you need to know what kind of list you're using. In general iterating it likely to be reasonably efficient, and random access may or may not be efficient. (It may be more efficient than iterating, but it's unlikely to be significantly more efficient.) In practice, my experience is that in most applications you actually have enough knowledge to make a reasonable judgement... but I'd still usually code for readability first.
As others have pointed out, if you do want to use random access to get at the elements, then it would be worth ensuring that your list implements the RandomAccess
interface too.