Java Byte Alignment

Generally, Java objects don't require manual byte alignment considerations as the JVM automatically optimizes this during compilation. However, languages like C/C++/C# need careful consideration of object field ordering to avoid wasting space. (Note: This article is based on JDK 1.8)

Object Structure

In the HotSpot JVM, objects in memory are divided into three regions: Header, Instance Data, and Padding.

Object Header

Alignment Rules

The 64-bit HotSpot VM reads data in minimum units of 8 bytes, so object sizes must be multiples of 8 bytes, with padding added if necessary.

Experimental Comparison

C/C++

In C/C++, inefficient property ordering in structures can increase the required storage space.

Test Code

Results

Therefore, arranging structure properties in a reasonable order is crucial in C/C++ programming. Fortunately, the JVM automatically adjusts property order to ensure minimal object storage space.

Java

Test Code

Results Memory Layout Diagram

In object memory layout, the JVM optimizes field ordering based on their types and sizes to reduce memory usage and meet alignment requirements. Key observations from the experiment include:

1. Field Order Adjustment: Despite different field declaration orders in Person and Person2 classes, the JVM ultimately adjusts field ordering, prioritizing larger fields (like int _int) to be placed first. This is because:

2. Memory Alignment Rules:

3. Optimization Results for Person and Person2: Regardless of field declaration order, the final memory layout is identical:

Additionally, through multiple tests, it's observed that JVM maintains the original property order for fields of the same size during byte alignment, such as long/double, int/float, and byte/boolean pairs.