Memory costs for declared but not used objects

  • Thread starter Thread starter Barbara
  • Start date Start date
B

Barbara

Hello
If I declare an object, ie "private TextBox tb;" and then do not use it in
program, is it
using same memory as "private TextBox tb=new TextBox();"?
 
No. The type declaration allocates four bytes to hold the ref for the
reference type (a few more bytes may be needed.) The "new" creates the
reference type in the heap and stores the pointer to it in the var. Without
the "new" your not instanciating an object.
private string s = null; // an int set to zero.
private string s = "win"; // the int is set to point to string object
instance in the heap (actual amount, not sure. I think length int, plus
chars, plus null terminated.)
 
Barbara said:
Hello
If I declare an object, ie "private TextBox tb;" and then do not use it in
program, is it
using same memory as "private TextBox tb=new TextBox();"?

No
It is allocated a "slot" on the stack which points to "null" on the heap.
When you instantiate it ( = new TextBox();) it creates a new object
(TextBox) on the heap and points to it.

HTH
JB
 
John Baro said:
No
It is allocated a "slot" on the stack which points to "null" on the heap.
When you instantiate it ( = new TextBox();) it creates a new object
(TextBox) on the heap and points to it.

HTH
JB

... but as the reference is private the optimizer will simply remove the
declaration, hence there is no cost at all.

Best Regards
- Michael S
 
Michael S said:
it

.. but as the reference is private the optimizer will simply remove the
declaration, hence there is no cost at all.

IF the ref is not instantiated later on.
 
Back
Top