Is the variable itself a memory consumption?

When we declare a variable, does the variable itself consume memory?

class IHaveNothing { } class IHaveNullFields { string @string = null; StringBuilder @StringBuilder = null; } class Program { static void Main(string[] args) { IHaveNothing nothing = new IHaveNothing(); IHaveNullFields nullFields = new IHaveNullFields(); } } 

Is an instance of nullFields more memory than an instance of nothing?

EDIT: What about null local variables, unlike null fields of a class, they also consume memory?

+7
c #
source share
5 answers

A variable is defined as a storage location. So the question is, does memory save a memory location?

When you say so, it seems obvious that the answer is yes. What else would be a storage location besides using memory?

It is not so easy. A local variable may not have memory at all; a local variable can be detected by jitter. In this case, it will not consume either a stack or a bunch of memory.

Why does it bother you? The way the CLR manages memory to create storage locations for variables is an implementation detail. If you are not writing unsafe code, you do not need to worry about it.

+9
source share

Yes, they consume the size of the machine pointer (at least).

+12
source share

IHaveNothing consumes 1 byte. It consumes bytes to provide a unique arrangement of variables.

IHaveNullFields consumes the size of two pointers.

Local null variables consume pointer size.

You can use Marshall.SizeOf to determine the size of your classes. See http://msdn.microsoft.com/en-us/library/y3ybkfb3.aspx

+3
source share

For value types, the variable contains the value itself, but for reference types, the object goes into the heap (managed memory space), and the variable contains a link pointing to the beginning of the memory block used to store the object.

The size of the pointer is determined by your system, on a 32-bit system, the reference pointer is 4 bytes, and for a 64-bit system, the pointer will be 8 bytes.

Since reference types require this overhead for each object, it is recommended that you specify a type that you are likely to create many times, for example Point , which is used in any paint program, you must make them value types using struct .

+2
source share

use CLR Profiler to determine the size of each type at runtime

+1
source share

All Articles