For (Something s: something.getList ())

I have a quick question Does it matter if I use a sentence this way:

for(Object obj : something.b.c.d.getList(){
...
}

      

or

List list = something.b.c.d.getList();
for(Object obj : list){
...
}

      

I'm wondering if someone else is faster

+3


source to share


2 answers


The main difference is stylistic. The semantics are pretty much the same. The only significant semantic difference is that in the second example, the link to the list is called and can be accessed both inside and after the loop:

List list = something.b.c.d.getList();
for(Object obj : list){
   if (list.contains(...)) { // inefficient, used purely as an illustration
      ...
   }
}
int n = list.size();

      



The above cannot be achieved in the first example without evaluating something.b.c.d.getList()

again.

If you are concerned that the first example is evaluating repeatedly something.b.c.d.getList()

, this is definitely not the case. Both examples evaluate the expression exactly once.

+3


source


There is probably no performance difference, but performance in general will depend on how expensive it is to access these fields (e.g. lazy loading from a framework). The fields will only be accessed once, regardless of which style you choose for that loop.

Both approaches are acceptable as long as both elements are something that can be used in an extended operator statement.



I wouldn't go into optimizations like this if the profiler didn't flag this particular area of ​​your code as a problem.

+1


source







All Articles