要[新增"还是不QUOT&;新"QUOT

由网友(太阳不懂月亮的空虚°)分享简介:有一个经验法则时要遵循使用新关键字,在声明对象时不?名单,其中,MyCustomClass> listCustClass =的GetList();或名单,其中,MyCustomClass> listCustClass =新的名单,其中,MyCustomClass>();listCustClass =...

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

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

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

解决方案 重要提醒 0新增 0风险

在您的情况似乎正在内部执行对象的实际创建你的的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.

阅读全文

相关推荐

最新文章