I have a string that contains comma seperated email addresses. I then load this into a string array, and from then populate a list which is easier to work with. Once the list is populated, I would like to be able to destroy the now unused string array, because the class still has a lot of work to do before the garbage collector will clean up this waste of memory.
How can I manually destroy this string array…
While reviewing the code, if you have a cleaner more efficient way of populating the list, recommendations are welcome.
Here is code:
public class EmailReportManager
{
private List<string> emailAddresses;
public EmailReportManager(string emailAddressesCommaSeperatedList)
{
loadAddresses(emailAddressesCommaSeperatedList);
}
private void loadAddresses(string emailAddressesCommaSeperatedList)
{
string[] addresses = emailAddressesCommaSeperatedList.Split(',');
for (int addressCount = 0; addressCount < addresses.Length; addressCount++)
{
this.emailAddresses.Add(addresses[addressCount]);
}
//Want to destroy addresses here.....
}
}
You can’t “destroy” the array. Options are:
Array.Clear, so that it won’t hold references to any strings any more. This won’t reclaim any memory.GC.Collectafter making sure you don’t have any references to the array any more. This will probably reclaim the memory (it’s not guaranteed) but it’s generally not a good idea. In particular, forcing a full GC regularly can significantly harm performance.It’s worth understanding that in your case you don’t need to set the array variable to null – it’s about to go out of scope anyway. Even if it wasn’t about to go out of scope, if it wasn’t going to be used in the rest of the method (and the JIT could tell that) then setting it to null would be pointless. The GC can pretty reliably tell when a variable is no longer relevant. It’s rarely a good idea to set a variable to null for the sake of GC – if you find you want to, that’s usually an indication that you could refactor your code to be more modular anyway.
It’s usually a good idea to just trust the GC. Why do you think the GC isn’t going to get round to reclaiming your array, and do you have a really good reason to care?