views:

79

answers:

2

In Java, which is faster:

  • Cloning an Object, then passing it to multiple listeners assuming the cloned object contains nothing more complicated than nested arrays, primitives and Strings
  • Using Streams to pass data through from one object to another?
+1  A: 

Cloning will be faster, assuming the implementation of clone() is reasonably sane.

If you think about it this is because clone() is a highly specialised function to do one thing only: create a copy of the object. It therefore doesn't have much overhead to worry about - typically all it does is a field by field copy to a new object instance.

But making your objects immutable and never having to worry about cloning instances again will be faster still :-)

mikera
p.s. clone() will also usually benefit from only doing a shallow copy of nested immutable objects e.g. Strings. Stream based methods will typically have to reconstruct such objects in their entirety.
mikera
+1  A: 

I would guess cloning is faster, because:

When you clone you create an object from another by instantiating it and it attributes. When you use streams you serialize an object and deserialize it (whereas Java also have to create an instance of the object). So when you use streams you have the overhead of serializing the objects.

Of course the implementation of clone() should not do something unusual which increases time to copy the objects. To clone an object with arrays, primitives and Strings should not consume so much time.

Daniel Engmann
You're right, we ran into major performance issues when using streams. The platform just couldn't handle the stress of serialization; too much reflection going on in the background. Overall, we found the fastest implementations were with the cloning.
Nathan Sabruka