问题描述
在.NET框架中,许多System.Collection类都有清除
它们的方法。是否有一个明显的优势,使用此而使用的新对象代替参考?
In the .NET framework, many of the System.Collection classes have Clear
methods on them. Is there a clear advantage on using this versus replacing the reference with a new object?
感谢。
推荐答案
您想使用清除
如果你有其它引用同一个对象,并且希望让他们都指向同一个对象。
You'd want to use Clear
if you have other references to the same object, and you want to keep them all pointing to the same object.
例如你可能有您存储任务做了工作队列。而在一个或多个线程你把工作项目拖出此队列中(当然你使用锁定,以确保您访问的队列中最多只有一个线程在同一时间)。如果在某些时候你想清空队列中,那么你可以使用清除
和所有线程仍将指向同一个对象。
For example maybe you have a worker queue where you store tasks to do. And in one or more threads you take work items out of this queue (of course you use locking to make sure you access the queue with at most one thread at a time). If at some point you want to empty the queue, then you can use Clear
and all threads will still point to the same object.
由于这里看到,当您使用清除
所有项目将被删除,而计数
将是0,但容量
将保持不变。通常情况下,容量
是不变是一件好事(为了提高效率),但也有可能是因为你有一吨的项目的一些极端情况下,你想的内存最终被释放
As seen here when you use Clear
all items will be removed, and the Count
will be 0, but the Capacity
will remain unchanged. Usually the Capacity
being unchanged is a good thing (for efficiency), but there could be some extreme case that you had a ton of items and you want that memory to be eventually freed.
上面的MSDN链接也提到,清除复杂度为O(n)的操作。而简单地替换引用将是一个O(1)操作,然后最终会被垃圾回收,但可能不是现在。用的参考文献还意味着,构成了容量的存储器需要被重新分配。
The MSDN link above also mentions that Clear is an O(n) operation. Whereas simply replacing the reference will be an O(1) operation and then eventually it will be garbage collected but possibly not right away. But replacing the reference also means that the memory that makes up the capacity will need to be re-allocated.
这篇关于使用"清除"方法与新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!