robjwilkins
robjwilkins

Reputation: 5652

Java pointer/reference memory cost

I have a Java object with 2 properties. One of this objects properties is a String. Virtually every instance of the object will have the same value (or one of 2 values)

For example:

public record Car (String modelId, String brand) {}

If I have millions of these objects, each with a different modelId, but with a brand = either Ford or Volkswagen, how does Java manage the brand property in terms of memory?

I think(?) there is just one instance of the Ford, and Volkswagen String objects, and each Car will have a pointer or reference to those Strings - is this correct?

My main question: Given we only have a pointer to the brand property, are the memory savings from removing the brand property fairly small? i.e. if I remove the String brand property from the Car I'm not going to save much in terms of memory despite having millions of Car instances?

bonus point: how much memory might I save by removing (?1 million) pointers from the memory stack?

Upvotes: 0

Views: 150

Answers (1)

user229044
user229044

Reputation: 239311

You can use string interning to ensure that each duplicate string points to the same memory.

Otherwise, if you create 1,000,000 Strings and set them to the value "Ford", you have created 1,000,000 copies of the bytes composing "Ford" in memory.

Upvotes: 2

Related Questions