title: Should variables be declared inside the loop or outside the loop in java
body: <p>I know <em>similar</em> question has been asked many times previously but I am still not convinced about when objects become eligible for GC and which approach is more efficient.</p>
  
  <p>Approach one:</p>
  
  <pre><code>for (Item item : items) {
      MyObject myObject = new MyObject();
      //use myObject.
  }
  </code></pre>
  
  <p>Approach Two:</p>
  
  <pre><code>MyObject myObject = null;
  for (Item item : items) {
      myObject = new MyObject();
      //use myObject.
  }
  </code></pre>
  
  <p>I understand: "By minimizing the scope of local variables, you increase the readability and maintainability of your code and reduce the likelihood of error". (Joshua Bloch).</p>
  
  <p>But How about performance/memory consumption? In Java Objects are Garbage collected when there is no reference left to the object. If there are e.g. 100000 items then 100000 objects will be created. In Approach One each object will have a reference (myObject) to it so they are not eligible for GC?</p>
  
  <p>Where as in Approach Two with every loop iteration you are removing reference from the object created in previous iteration. so surely objects start becoming eligible after the first loop iteration.</p>
  
  <p>Or is it a trade off between performance and code readability &amp; maintainability?</p>
  
  <p>What have I misunderstood?</p>
  
  <p>Note:
  Assuming I care about performance and myObject is not needed after the loop.</p>
  
  <p>Thanks In Advance</p>