-1

Back to the basics question

Which one of the 'WHILE' loops below is efficient memory wise

     SomeObject someObject;
     while (iterator.hasNext()) {
         someObject = iterator.next();
     }

OR

while (iterator.hasNext()) {
  SomeObject   someObject = iterator.next();
 }
TheMonkWhoSoldHisCode
  • 2,182
  • 3
  • 26
  • 40

4 Answers4

2

Both are practically the same. The only thing that gets created here is the reference. Create it once or many times it will never have any practical hit on the memory or execution speed.

Vivek V K
  • 1,100
  • 2
  • 15
  • 33
1

From a design and (GC) perspective : Assuming the Collection on which you are iterating gets GCed after the while loop.

SomeObject someObject; // You will still have a reference to the last SomeObject outside the while loop

 while (iterator.hasNext()) {
     someObject = iterator.next();
 }

//the Object being referenced by someObject will not be ready for GC here. because it will still be having a reference to it.

OR

while (iterator.hasNext()) {
  SomeObject   someObject = iterator.next();
 }
// someObject will make no impact on the GC of the object is points to.
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • looking at the code, the collection can only have a scope equal to or bigger than the scope of SomeObject so the scenario where the collection is GCed before SomeObject cannot happen. – Vivek V K Jul 16 '14 at 06:49
  • @VivekVK - what if I pass / return the variable `someObject` to another method and if the collection was created in this method... ?. This will directly affect GCing of the last object in the collection right? – TheLostMind Jul 16 '14 at 06:53
  • yup did not think of that. sorry. – Vivek V K Jul 16 '14 at 06:57
0

Both the code snippets are making no difference except the thing that in first case you can use the object reference someobject even after the while block has completed its iterations.

nobalG
  • 4,544
  • 3
  • 34
  • 72
  • yeah you can. But that would only be pointing to the last object in the iterator so I don't think it exactly a "use" unless you specifically need the last one which is usually uncommon. – Vivek V K Jul 16 '14 at 06:45
  • @VivekVK in complete agreement with you except the last word 'uncommon' – nobalG Jul 16 '14 at 06:47
-3

The 1st will be more efficient in Java, as a new object is not being created every time the loop runs. This means that the garbage collection has to run more often to delete the old objects. As a general rule (even in non-garbage collected languages) it is more efficient to reuse old objects than it is to delete old ones and create new ones

Matt
  • 968
  • 2
  • 13
  • 22