Domanda

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?

È stato utile?

Soluzione 2

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.

Altri suggerimenti

As @Tim Schmelter says in the comment, assigning a value of Nothing is the VB.NET equivalent for default(T) in C#.

An Integer will always occupy 4 bytes, 32 bits. Doesn't matter which value you put into it.

However, if you have a reference, it will occupy 4 bytes in a 32-bit process and 8 in a 64-bit process, also regardless of which value you put into it. An Integer, or System.Int32, however, is not a reference type.

Nothing here doesn't mean "no reference" (as I originally thought), just that you're assigning the default value for the type into the variable. In this case, the default for Integer is 0.

So, your variable occupies 4 bytes because it is an System.Int32. The code you have will just assign the value 0 to it.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top