Search code examples
javaperformancestreamcloning

Which is faster: Cloning or using Streams?


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?

Solution

  • 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.