哪个更快:克隆还是使用 Stream?
在 Java 中,哪个更快:
- 克隆一个对象,然后将其传递给多个侦听器,假设克隆的对象不包含比嵌套数组、基元和字符串更复杂的内容
- 。使用流将数据从一个对象传递到另一个对象?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我猜克隆会更快,因为:
当你克隆时,你通过实例化另一个对象及其属性来创建一个对象。
当您使用流时,您可以序列化一个对象并反序列化它(而 Java 还必须创建该对象的实例)。因此,当您使用流时,您会产生序列化对象的开销。
当然,clone() 的实现不应该做一些不寻常的事情,这会增加复制对象的时间。使用数组、基元和字符串克隆对象不应该花费太多时间。
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.
假设clone()的实现相当合理,克隆会更快。
如果你仔细想想,这是因为clone()是一个高度专业化的函数,只做一件事:创建对象的副本。因此,它不需要担心太多开销 - 通常它所做的只是逐个字段复制到新的对象实例。
但是,使您的对象不可变并且不必再次担心克隆实例会更快:-)
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 :-)