什么更有效率?清空一个对象或创建一个新对象? [英] what's more efficient? to empty an object or create a new one?

查看:144
本文介绍了什么更有效率?清空一个对象或创建一个新对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

'新'有多贵?我的意思是,我是否应该重新使用相同的对象,或者如果对象是超出范围,它与清空它是一样的吗?

how expensive is 'new'? I mean, should I aim at reusing the same object or if the object is 'out of scope' it's the same as emptying it?

例如,假设一个方法创建一个列表:

example, say a method creates a list:

List<Integer> list = new ArrayList<Integer>(); 

在方法结束时列表不再使用 - 这是否意味着没有内存分配给它或它是否意味着有一个空指针(因为它是'创建')。

at the end of the method the list is no longer in use - does it mean that there's no memory allocated to it anymore or does it mean that there's a null pointer to it (since it was 'created').

或者,我可以向方法发送一个'list'并在方法的末尾清空它: list.removeAll(list) ; 这会从内存的角度来看有什么不同吗?

Alternately, I can send a 'list' to the method and empty it at the end of the method with: list.removeAll(list); will that make any difference from memory point of view?

谢谢!

推荐答案

它是一个数组列表,所以创建一个新对象意味着分配一块内存并将其清零,以及任何簿记开销。清除列表意味着清零存储器。此视图将使您相信清除现有对象的速度更快。但是,JVM很可能已经过优化,可以快速进行内存分配,因此可能这些都不重要。所以只需编写清晰易读的代码,不要担心。毕竟这是java,而不是c。

its an array list, so creating a new object means allocating a slab of memory and zeroing it, plus any bookkeeping overhead. Clearing the list means zeroing the memory. This view would lead you to believe that clearing an existing object is faster. But, it's likely that the JVM is optimized to make memory allocations fast, so probably none of this matters. So just write clear, readable code, and don't worry about it. This is java after all, not c.

这篇关于什么更有效率?清空一个对象或创建一个新对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆