0

A very basic question:

//List<Students> b;
for(int i=0;i<count;i++){
  List<Students> b = school.getstudents(classID);
} 

Although it is recommended to keep the scoping as small as possible,is there any advantage of a outer scope variable when we are looping through a possibly unbounded counter.
Is there any difference in the instances created and promoted from the young generation by either of the approaches?
To be more specific, in case we are looping through a count on a million students - would we be reducing the possibility of higher object promotions and full GC if we declared the variable outside

IUnknown
  • 9,301
  • 15
  • 50
  • 76
  • 1
    Are you talking about hoisting *just* the variable out of the loop, or also the call to `school.getstudents()`? – Oliver Charlesworth Mar 30 '17 at 12:34
  • Why... why would you fetch the same value over and over again? What's the point of this loop? – domsson Mar 30 '17 at 12:35
  • 3
    Possible duplicate of [Declaring variables inside or outside of a loop](http://stackoverflow.com/questions/8803674/declaring-variables-inside-or-outside-of-a-loop) – Mike Nakis Mar 30 '17 at 12:35
  • Repeated variable declaration should be optimized by the compiler. Repeated variable initialization can't be avoided without changing the algorithm itself. – Spidey Mar 30 '17 at 12:47
  • To be more specific, in case we are looping through a count on a million students - would we be reducing the possibility of higher object promotions and full GC if we declared the variable outside – IUnknown Mar 30 '17 at 12:54
  • The way you create the reference has nothing to do with garbage collection. – RealSkeptic Mar 30 '17 at 13:45

0 Answers0