0

In my code creating an object is extremely expensive and the memory required is quite large. I need to create it about a 100 times for testing my product. If I write it as so

for(int i =0; i < length; i++){

Object ob = new Object();
//do something with ob

Object2 ob2 = new Object2();
//do more with ob2

}

Will this create a new ob, ob2 every time the for loop is run? I need them to be set to null at the end of the for loop after execution else my test results will come out wrong. According to this it doesn't matter so I'm slightly confused.

I think it should destroy them at the end of the for loop.

Community
  • 1
  • 1
Sood
  • 149
  • 1
  • 1
  • 11

2 Answers2

3

You do not need to set ob and ob2 to null.

In your code above after each iteration of your for-loop you can no longer access the ob and ob2 objects from the previous iteration. This means that they will be garbage collected eventually.

However, if they implement IDisposable you should dispose them before the end of each iteration.

Saeed Jahed
  • 821
  • 5
  • 8
0

Yes, objects ob and ob1 are created and destroyed in the scope of your for loop; so new objects are created for both on every loop iteration.

If you need them to be null at the end of the loop within the loop, but before next loop iteration runs, then set them to null:

ob = null;
ob1 = null;

However, it seems unnecessary (except that your original post says you need to do so). The objects are destroyed on each loop iteration end, and will not exist once the loop is complete.

CoolBots
  • 4,770
  • 2
  • 16
  • 30