Reputation: 47
List<object> obj = new List<object>();
List<objectTypeof_d> list = new List<objectTypeof_d>();
foreach (Object o in obj)
{
d = new Object();
d = o;
list.add(d);
}
I am trying to understand that when in loop we declare d = new Object();
then every looping it create new instance of object.It is better coding or below is right.
List<object> obj = new List<object>();
List<objectTypeof_d> list = new List<objectTypeof_d>();
foreach (Object o in obj)
{
d = new Object();
d = o;
list.add(d);
d = null;
}
It's just for understanding ignore syntax,or assume object add into list in a loop. after adding can we set it to null or not. For memory optimization only.
Upvotes: 0
Views: 613
Reputation: 216273
It seems that you haven't grasped the concept of references.
I suggest to read this Values vs Reference Types
In your first example you create a new instance of an object calling d = new Object();
This variable d references a memory area to store your object (I suppose you use Object here just for example).
Now the following line changes the value stored in d (a reference value) to the reference value stored in o. Thus the first reference is lost and ready to be garbage collected.
Said that, it is clear that your real optimization here, is to remove the variable d and the call to new object()
. (And also the call to d = null;
)
Anyway, also maintaining your actual code, setting the variable d = null;
doesn't change your memory footprint. The real cleanup of the memory is executed when the garbage collector runs and this time is chosen by the system when there is need for that process to run.
It is often a bad idea to think "I need more free memory, let's force a garbage collector run".
Upvotes: 1
Reputation: 37000
new
will allways create a new instance, be it in a loop or not. So in your case you´re creating multiple instances of Object
and throw them away as you´re overwriting the only reference to that instance by the line d = o
. I suppose you can simply remove that line and write this instead:
foreach (Object o in obj)
{
list.add(o);
}
Or even simpler:
list.AddRange(obj);
However as you never add anything to obj
(bad name for a list BTW), the loop won´t execute at all.
Upvotes: 2