处理后将对象设置为空是否是一种很好的做法? [英] Is it a good practice to set an object to null after processing?
问题描述
我有这样的场景:
public void processData(String name,String value){
/ *第1行* / MyDTO dto = new MyDTO();
/ *第2行* / dto.setName(name);
/ *第3行* / dto.setValue(value);
/ *第4行* / sendThroughJMSChannel(dto);
/ *第5行* / dto = null; //作为最佳做法,我应该这样做吗?
$ / code>
在我的程序第4行我不需要 dto
作进一步处理。作为最佳做法,我应该如第5行中设置 dto
为 null
或忽略它通过设置为 null
,我期待快速垃圾回收。是否正确?
不,不要将局部变量设置为 null
通过GC加速他们的收集:编译器非常聪明,无需您的帮助就可以解决问题; null
赋值只会让你的代码看起来很脏。
非本地人是另一回事:如果你有一个可能停留时间超过必要的成员变量,将其设置为 null
并防止 lingerer内存泄漏是一个好主意。 p>
I have scenario like this:
public void processData(String name,String value) {
/* line 1 */ MyDTO dto = new MyDTO();
/* line 2 */ dto.setName(name);
/* line 3 */ dto.setValue(value);
/* line 4 */ sendThroughJMSChannel(dto);
/* line 5 */ dto = null; //As a best practice, should I do this ?
}
In my program after line 4 I don't require dto
for further processing. As a best practice, should I set dto
to null
as in line 5 or ignore it?
By setting it to null
, I'm expecting fast garbage collection. Is it correct?
No, do not set local variables to null
to hasten their collection by the GC: the compiler is smart enough to figure it out without your help; the null
assignments will only make your code look dirty.
Non-locals are a different story: if you have a member variable that might stay around for longer than necessary, it is a good idea to set it to null
and prevent lingerer memory leaks.
这篇关于处理后将对象设置为空是否是一种很好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!