Field layout code makes no use of the super-class gaps. Which means if we have the space in superclass area, we don't use it. For example:
public static class A {
long f;
}
public static class B extends A {
long f;
}
public static class C extends B {
long f;
int a;
}
...is laid out like this:
jol.Main_05_InheritanceBarrier.C object internals:
OFFSET SIZE TYPE DESCRIPTION VALUE
0 12 (object header)
12 4 (alignment/padding gap)
16 8 long A.f N/A
24 8 long B.f N/A
32 8 long C.f N/A
40 4 int C.a N/A
48 4 (loss due to the next object alignment)
Space losses: 4 bytes internal + 4 bytes external = 8 bytes total
It seems legal to lay out the fields like this (i.e. move the C.a up to fill the gap):
jol.Main_05_InheritanceBarrier.C object internals:
OFFSET SIZE TYPE DESCRIPTION VALUE
0 12 (object header)
12 4 int C.a N/A
16 8 long A.f N/A
24 8 long B.f N/A
32 8 long C.f N/A
Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
That saves 8 bytes per instance. While this is arguably hard to do with current field layout code. By Java rules, C.a is not visible in A anyway, and there is no legal way to hijack its value. Am I overlooking something?
public static class A {
long f;
}
public static class B extends A {
long f;
}
public static class C extends B {
long f;
int a;
}
...is laid out like this:
jol.Main_05_InheritanceBarrier.C object internals:
OFFSET SIZE TYPE DESCRIPTION VALUE
0 12 (object header)
12 4 (alignment/padding gap)
16 8 long A.f N/A
24 8 long B.f N/A
32 8 long C.f N/A
40 4 int C.a N/A
48 4 (loss due to the next object alignment)
Space losses: 4 bytes internal + 4 bytes external = 8 bytes total
It seems legal to lay out the fields like this (i.e. move the C.a up to fill the gap):
jol.Main_05_InheritanceBarrier.C object internals:
OFFSET SIZE TYPE DESCRIPTION VALUE
0 12 (object header)
12 4 int C.a N/A
16 8 long A.f N/A
24 8 long B.f N/A
32 8 long C.f N/A
Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
That saves 8 bytes per instance. While this is arguably hard to do with current field layout code. By Java rules, C.a is not visible in A anyway, and there is no legal way to hijack its value. Am I overlooking something?
- duplicates
-
JDK-8237767 Field layout computation overhaul
-
- Resolved
-
- relates to
-
JDK-8024912 Subclass instance fields are laid out with alignment gaps
-
- Closed
-