Defining a "for-each loop", it is better use this convention:
Case 1
for (String s : xxx.getList())
or this:
Case 2
List<String> list = xxx.getList();
for (String s : list)
In Case 1, how many times the method getList() is invoked? One time every loop or only one time at the beginnning?
Thanks
Never spend time thinking about this type of optimisation.
1) If you can think of a one line change which seems more efficient but functionally equivalent, its certain that the people who write the JIT compiler also thought of it. And they will compile to the same bytecode.
2) Readability is far more important than performance in all but the most critical loops. You should use case two only if you intend to use the list for something else which is outside the scope of the for loop, and your for loop alters the list. In that case it is semantically clearer to carry the altered list than to repeatedly call xxx.getList(), as a programmer looking at a part of the function may not realise that you have edited the list in xxx further up in the same function.
3) There are few hard and fast rules in this type of programming, and opinions on what represents "readability" vary.
Remember that a compiled language is not the same as an interpreted language, and the code you write is not a literal script book for the processor. Almost every small optimisation that you can imagine, and a lot that you cannot, will be made by the Compiler. Moreover, lots of standard programming patters of high complexity can be optimised by the compiler, when attempts to "optimise it" on your own will just lead to the compiler `getting confused', not recognising that this is a standard pattern, and failing to optimise when it should.
========================
In the comments slim has pointed out that there is another case for using case 2 - if you have several for loops and getList is an expensive operation which constructs the list on request, rather than just returning an existing object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With