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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You’d want to use
Clearif 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
Clearand all threads will still point to the same object.As seen here when you use
Clearall items will be removed, and theCountwill be 0, but theCapacitywill remain unchanged. Usually theCapacitybeing 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.