In C and C++, the compiler is not allowed to reorder data members of structs, so if you’re not careful with how you order them, you end up wasting space. For example:
struct S {
int i;
void *p;
int i2;
};
On a platform with 32-bit ints and 64-bit pointers, i will be placed first, followed by 32 bits of padding so that p can be 64-bit–aligned. i2 then takes up half of the next word, followed by another 32 bits of padding. The resulting struct is 24 bytes long, whereas if p were declared first, it would be only 16 bytes long. If you have a lot of these structs in an array, finding and removing the padding can sometimes be an important optimization, to save memory and reduce cache churn.
I’m curious to know if Java has the same feature. Are unboxed types (such as int and boolean) the same size as references or smaller? And if they’re smaller, is the compiler allowed to reorder them to avoid inserting padding to align subsequent fields? Finally, if it is, do any compilers do this?
I don’t have a particular optimization need for this right now, I’m just curious to know if I should bear this in mind when choosing what order to declare my fields, like I do in C.
inttypes are always 32-bit and references are usually 32-bit even in 64-bit JVMs.On the down side, Java has a 8-12 byte header at the start of each object and uses an 8-byte alignment. BTW some C++ environments have a 16-byte alignment.
You can expect them to be smaller for boolean, byte, char and short, but the primitives can be larger for long and double than a reference.
The JIT can re-organize the fields or even optimize them away.
The
javaccompile does next to no optimizations and looking at the byte code will give you little clues as to what will happen at runtime. The JIT can optimize the fields in an objects anyway it chooses.IMHO, You can assume that just about every optimization trick you might have used in C no longer applies in Java. Of the few that do, they may not be exactly the same.
You should assume the JIT will optimize the code as required and use profilers to determine if and when you have a problem. Only then consider altering the code for performance reasons.