I have a question on custom cloning. I am giving a simplified example of object structure in my project.
Suppose I have following classes:
My project requires me to clone Product instances in some cases. There can be more than 10000 objects of Product class at one time in session. Standard cloning can be memory consuming if I clone every variable. I analyzed that except customIngredients and location variable, all other variable values remain same. So I think if I just clone customIngredients and location values and copy the same references over in cloned instances, it should save me memory.
I am thinking to clone using standard clone method first (so that all primitives are immutable references are also cloned), and later call clonedInstance.setXXX(this.getXXX()) method for each readonly attribute to save memory, like this.
Another approach can be this:
Now my questions:
1. Do you think I am thinking right to save memory this way?
2. Is there another approach to not to clone readonly attributes, except to make them final?
3. Which of above 2 approached will be better?
Are you really suggesting that 10,000 instances takes up a lot of memory on a modern PC? If you said 10,000,000 I would be more impressed about lots of memory.
Whether you clone or not, and how, is a design problem. How many of your fields are immutable, because they only need to have their references copied? There is no need for cloning immutable classes. They will therefore not occupy additional memory. Only about 32 bits for the copied reference.
Similarly for primitives, they cannot be cloned and can simply be copied.
Mutable reference types as fields, however, are probably best being copied (I won't presume to tell you how to copy them). I am a bit worried about copying read-only attributes. If thy are mutable reference types, then a get method can allow the reference to be modified and the state of the object and its clone to be alteredYou should see the problem there . . .
Joined: Jul 10, 2008
You are right Ritchie. Actually my question was wrong. I am talking about saving memory from immutable objects, which in fact are already not cloned by Java. And I agree with you about always deep cloning mutable objects.