Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

new keyword wasting memory? 1

Status
Not open for further replies.

ajikoe

Programmer
Apr 16, 2004
71
ID
hallo,

If I have a class for example :

Class A{
int i;
public A(int myi){
i = myi;
}
}

and in my main class I can write:
A a1 = new A(1);//assigning a1.i = 1
a1 = new A(2); //assigning a1.i = 2

the question :
If I use the above method to change the value of i, is it wasting the computer memory?

Sincerely Yours,
Pujo Aji
 
It's definitely slower, and will certainly impact memory usage in the short term.

What will happen is that the old A1 will be disposed (put on the list for the garbage collector to free it), a new memory block will be reserved, the constructor will be called, and the result will be assigned to variable a1.

Since a1 is a local variable, it lives in memory generation 0, and so this (old) block of memory will be among the first blocks freed & compacted the next time the garbage collector runs. As a result, your memory usage will be higher until a GC runs. This probably isn't a big deal on a desktop PC, but has significant impact to a PocketPC running the compact framework.

There may be valid design reasons why you'd do it this way (allocating a new instance), but most of the time if you want to change the value of i, you'd just provide a property to do it.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top