开发者

Does a variable itself consume memory?

When we declare a variable, does the variabl开发者_如何学JAVAe 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();
    }
}

Does the instance nullFields consume more memories than the instance nothing ?

EDIT: How about null local variables as opposed to class' null fields, do they consume memory too?


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


A variable is defined as a storage location. So the question is: does a storage location consume memory?

When you say it that way it sounds obvious that the answer is yes. What else would a storage location do other than consume memory?

It's not as simple as that. A local variable can consume no memory at all; a local variable might be enregistered by the jitter. In that case it would consume neither stack nor heap memory.

Why do you care? The way that the CLR manages memory to make storage locations for variables is an implementation detail. Unless you're writing unsafe code, you don't have to worry about it.


IHaveNothing consumes 1 byte. It consumes a byte in order to ensure that the variable location is unique.

IHaveNullFields consumes the size of two pointers.

null local variables consume the size of a pointer.

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


For value types, the variable contains the value itself, but for reference types, the object goes onto the heap (the managed memory space) and the variable contains a reference pointing to the start of the block of memory used to hold 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.

Because reference types require this overhead per object, the recommendation is that for a type which you're likely to create many many times, such as the Point type used in any drawing program, you should make them value types using the struct keyword.


use CLR Profiler to determine each type size at runtime

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜