Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the "clear" method vs. New Object

Tags:

c#

.net

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?

Thanks.

like image 997
Daisuke Shimamoto Avatar asked Jun 24 '10 00:06

Daisuke Shimamoto


People also ask

What does Clear () do in C#?

This method(comes under System. Collections namespace) is used to remove all the objects from the Stack. This method will set the Count of Stack to zero, and references to other objects from elements of the collection are also removed.


2 Answers

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.

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.

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.

like image 136
Brian R. Bondy Avatar answered Sep 29 '22 02:09

Brian R. Bondy


Brian is correct but to be more specific, the Clear method removes all items from the current instance of the collection. Instantiating a new collection and assigning its reference to your variable will give you an entirely new instance altogether and may cause some unintended consequences depending on whether or not other people are holding a reference to the old instance. If another thread has a reference to that collection they will still hold a reference to the old collection even though you have created a new instance.

like image 31
Andrew Hare Avatar answered Sep 29 '22 04:09

Andrew Hare