Java virtual machines may use int-sized width for short fields as well (this depends on their internal implementation). Only the arrays (short[]) are exception, where it is always guaranteed that they take less space than an int[] internally as well). What about Dalvik?
E.g. I have a class which contains 50 fields of type short. Sometimes in my application, 10000 of these classes exist. This means that the short fields should use 1MB of memory, but if Dalvik uses 4 bytes for short values internally, then this will be 2MB memory usage.
How much memory should I expect Dalvik to use? (This refers to its internal memory use, and I’m aware of the fact that it might not be reflected by the system memory usage, e.g. because Dalvik already reserved a higher amount of memory from the system.)
In dalvik, double and long fields are 8 bytes, everything else (including short) is 4 bytes.
On the other hand, short arrays take 2 bytes per element (in addition to up-front space for the array+object bookkeeping).
Arrays
The
new-arrayopcode callsdvmAllocArrayByClass(line 71) to allocate space. This then callsdvmAllocPrimitiveArray(line 113). In the switch indvmAllocPrimitiveArray, the ‘S’ case is used for a short array. You can see it callsallocArray(line 38) with width=2.Within
allocArray, it does the following computation to calculate the size size of the array:For a short, on a 32 bit system, this calculation would be:
Short arrays take 2 bytes per element.
Fields
The
new-instanceopcode callsdvmAllocObject(line 181) to allocate space for the new object. The size that is allocated is based on theobjectSizefield ofClassObject.objectSizeis set incomputeFieldOffsets(line 3543). If you find every instance of where fieldOffset is incremented in this function, you will notice it is always incremented in steps of 4 bytes.Short fields take 4 bytes.