Fast deep copy

D

Dlugi

Hi,

I need fast deep copy algorithm for cache. For now I was using
serialization to make deep copy of object, and this solution cause 30
times more overhead then disk access :/

TIA
 
S

Stefan Ram

Dlugi said:
I need fast deep copy algorithm for cache. For now I was using
serialization to make deep copy of object, and this solution cause 30
times more overhead then disk access :/

Using reflection you can copy all fields (recursively, but
keeping a list of objects already copied so as to not copy
them again in the case of cycles).

If you can modify the classes, make each class implement a
»deepCopy« method instead (This should also accept a Map of
objects already copied, if the data structure should contain
cycles).
 
D

Dlugi

It's not actual no longer, I implement deep copy in clone method and it
is 1000 times faster than serialization!!
 
D

Daniel Pitts

It's not actual no longer, I implement deep copy in clone method and it
is 1000 times faster than serialization!!

Careful, clone doesn't do a deep copy automatically.
All the objects you clone will have a shallow copy only, unless you
override the clone method.
 
R

Roedy Green

It's not actual no longer, I implement deep copy in clone method and it
is 1000 times faster than serialization!!

If you have any immutable objects in the tree, they likely don't need
to be duplicated.
 
N

nebulous99

If you can modify the classes, make each class implement a
»deepCopy« method instead (This should also accept a Map of
objects already copied, if the data structure should contain
cycles).

Why use a Map instead of a Set for this?

I do prefer this to using the clone() method, as you'll be reminded
when writing recursive deepCopy() methods that there's no deepCopy()
on List, etc.; writing a recursive clone() method you may well
unthinkingly invoke clone() on a collection and get a shallow copy
instead of a won't compile as a result. Obvious bugs are better than
subtle bugs, especially ones that may initially be completely silent.

You also don't need to copy Strings and other value objects that are
not mutated, unless there's a need for the original and the copy of
the value object to compare != for some reason. Otherwise just copy
the reference.

Mutable objects that are semantically-constant might also not need
copying. (E.g. a protocol handler object that is stateful, but where
this is logically always the same object and it makes sense for both
copies of your larger structure to share the same one rather than use
two separate ones.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,172
Latest member
NFTPRrAgenncy
Top