开发者

Which is faster: Cloning or using Streams?

开发者 https://www.devze.com 2023-01-02 04:58 出处:网络
In Java, which is faster: Cloning an Object, then passing it to multiple listeners assuming the cloned object contains nothing more complicated than neste开发者_开发百科d arrays, primitives and Stri

In Java, which is faster:

  • Cloning an Object, then passing it to multiple listeners assuming the cloned object contains nothing more complicated than neste开发者_开发百科d arrays, primitives and Strings
  • Using Streams to pass data through from one object to another?


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.


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 :-)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号