Hi,
Does anyone know how much memory is taken up when you create a reference type variable?
String s = "123";
How much memory would 's' take up as a reference, not the data pointing to it?
Hi,
Does anyone know how much memory is taken up when you create a reference type variable?
String s = "123";
How much memory would 's' take up as a reference, not the data pointing to it?
Depending on whether you're on a 32- or 64-bit machine, it'll be either a 32- or 64-bit pointer.
The size of the reference itself will depend on your processor architecture - 4 bytes on 32-bit, 8 bytes on 64-bit.
This is broken down in the following fashion:
String s = "123";
The variable s: this will consume the native pointer size on the current architecture (which is considered 32bit if the OS is 32bit or the process is executing under WoW64), so 32 bits or 64 bits accordingly. In this case s is on the stack, where you to place the string into an array then that space would be consumed on the heap.
The fact that string is an object: 8 bytes of overhead split 4 bytes for the method table, which doubles as the indication of what actual type an object is plus 4 bytes for some housekeeping bits and the syncblock that allows it to be used as the target of a lock statement.
Strings further contain the following:
The string is always terminated by the null character so that it can be used directly with C-Style string apis, characters are UTF-16 so two bytes.
string may consume up to twice the amount of memory required to actually hold the character array needed owning to the way StringBuilder's work
Thus the string itself will consume between 16 + (2*n) + 2 and 16 + (4*n) + 2 bytes on the heap depending on how it was created.
This will be complicated by string interning (where two separate instances end up pointing to the same string since it is immutable)
for more discussion of this take a look at this article