Search code examples
.netmemory-managementnullnative

How much memory does Nothing take?


I just wondered, if I have a variable and I assign Nothing (or Null) to it, how much memory does the variable occupy?

For example

Dim i as Integer = Nothing

Does the variable use no memory? Or the size of the integer, 4 byte? Basically I think that it means the value is not assigned and therefore there is no value anywhere in memory so it should take no memory. However there is the information stored that the variable is nothing, so this information must take memory, right? Is there a difference between .NET and native languages? Or between value and reference types?


Solution

  • Generally speaking: A reference to Null takes only the space of the reference itself on the stack. Which should be 8 byte on a 64 bit system.

    In your particular case: Note the difference between boxed and unboxed values! A boxed integer is a reference to an instance of the Integer class. The instance was not created (Nothing), so it takes no space. The reference takes 8 bytes.

    If you were using an unboxed value (int), it would take the space of an int (struct), which is exactly 4 bytes. Note that there is no reference involved here.

    It would be an easier example to use a 'regular' class instead of the special case with Integer. For instance, consider

    Object o = new Object()
    

    This takes 8 bytes on the stack, even though o itself is empty.