Reputation: 1858
While searching whether this was already answered, I found Are class members guaranteed to be contiguous in memory?, but that deals with C++, not Java.
To provide context, I have a background in Go and I'm learning Java. I know that with Go, I can write a struct using pointers like this:
type myStruct struct {
firstMember *string
secondMember *int
}
But when studying Go in detail, I often read about this being a bad idea unless you really need them to be pointers, because it means the values for each member can be spread anywhere across dynamic memory, hurting performance because it's less able to take advantage of spatial locality in the CPU.
Instead, it's often recommended to write the struct this way, without using pointers:
type myStruct struct {
firstMember string
secondMember int
}
As I learn how to effectively write Java, I'm curious if I have this same tool in my toolset when working with Java. Since I don't have the ability to use pointers (because every variable whose type is a class is a reference to that class, effectively a pointer), I can only write the class using String
and int
:
class MyClass {
String firstMember;
int secondMember;
}
Realizing that this was the only way to write a class for my data structure led me to the question posed.
Upvotes: 0
Views: 260
Reputation: 1113
But when studying Go in detail, I often read about this being a bad idea unless you really need them to be pointers, because it means the values for each member can be spread anywhere across dynamic memory, hurting performance because it's less able to take advantage of spatial locality in the CPU.
You have no choice in Java.
class MyClass {
String firstMember;
int secondMember;
}
The String-valued member is, and can only be, a reference (i.e., effectively a pointer). The int-valued member is a primitive value (i.e., not a pointer).
The Java world is divided into primitive values and objects (of some class, or arrays, and so on). Variables for the former types are not references, variables for the latter types are references.
The Java Language Specification does not talk about object layout at all; that's not a concept that appears in the language.
The JVM Specification specifically says
The Java Virtual Machine does not mandate any particular internal structure for objects.
Pragmatically, you might guess that the body of a class instance is a single piece of memory, but that still leaves open the questions of alignment, padding, and ordering or members (no reason to keep source-code order that I can see, and some reasons to reorder).
Upvotes: 1