要[新增"还是不QUOT&;新" [英] To "new" or not to "new"

查看:137
本文介绍了要[新增"还是不QUOT&;新"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个经验法则时要遵循使用关键字,在声明对象时不?

 名单,其中,MyCustomClass> listCustClass =的GetList();
 

 名单,其中,MyCustomClass> listCustClass =新的名单,其中,MyCustomClass>();
listCustClass =的GetList();
 

解决方案

在您的情况似乎正在内部执行对象的实际创建你的的GetList()方法。所以,你的第一个样品将是正确的使用方法。

在创建,您的名单,其中,MyCustomClass> 存储在堆栈,和你的 listCustClass 是一个简单的参考到该新对象。当您设置listCustClass为的GetList()的引用指针 listCustClass 被丢弃,与参考指针,无论换成的GetList()返回(可能为空)。当发生这种情况你原来的名单,其中,MyCustomClass> 仍是堆,但没有对象指向它,所以它只是在浪费资源,直到垃圾收集器来临时,并清除它

要概括起来每次创建新的对象,然后放弃它,就像第二个例子中,你基本上通过填写无用的信息堆内存浪费。

Is there a rule of thumb to follow when to use the new keyword and when not to when declaring objects?

List<MyCustomClass> listCustClass = GetList();

OR

List<MyCustomClass> listCustClass = new List<MyCustomClass>();
listCustClass = GetList();

解决方案

In your scenario it seems that the actual creation of the object is being performed inside your GetList() method. So your first sample would be the correct usage.

When created, your List<MyCustomClass> is stored in the heap, and your listCustClass is simply a reference to that new object. When you set listCustClass to GetList() the reference pointer of listCustClass is discarded and replaced with a reference pointer to whatever GetList() returns (could be null). When this happens your original List<MyCustomClass> is still in the heap, but no objects point to it, so its just wasting resources until the Garbage Collector comes around and cleans it up.

To sum it up everytime you create a new object then abandon it, like the second example, you're essentially wasting memory by filling the heap with useless information.

这篇关于要[新增&QUOT;还是不QUOT&;新&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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