Memory required for 'short' fields in Dalvik?
android, dalvik, java
Solution
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-array` opcode calls `dvmAllocArrayByClass` (line 71) to allocate space. This then calls `dvmAllocPrimitiveArray` (line 113). In the switch in `dvmAllocPrimitiveArray`, the 'S' case is used for a short array. You can see it calls `allocArray` (line 38) with width=2.
Within `allocArray`, it does the following computation to calculate the size size of the array:
size_t elementShift = sizeof(size_t) * CHAR_BIT - 1 - CLZ(elemWidth);
size_t elementSize = length << elementShift;
size_t headerSize = OFFSETOF_MEMBER(ArrayObject, contents);
size_t totalSize = elementSize + headerSize;
For a short, on a 32 bit system, this calculation would be:
size_t elementShift = (4 * 8) - 1 - 30; //== 1;
size_t elementSize = length << 1; //i.e. length * 2
size_t headerSize = <some constant value>;
size_t totalSize = length*2 + <some constant value>;
Short arrays take 2 bytes per element.
Fields
The `new-instance` opcode calls `dvmAllocObject` (line 181) to allocate space for the new object. The size that is allocated is based on the `objectSize` field of `ClassObject`. `objectSize` is set in `computeFieldOffsets` (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.
Problem
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.)