Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any performance benefits to removing items from C# Dictionary after lookup if they only need to be read once

I have a Dictionary of objects with strings as the keys. This Dictionary is first populated with anywhere from 50 to tens of thousands of entries. Later on my program looks for values within this dictionary, and after having found an item in the dictionary I no longer have any need to persist the object that I just found in the dictionary. My question then is, would I be able to get better total execution time if I remove entries from the dictionary once I no longer have use for them, perhaps cutting down memory usage or just making subsequent lookups slightly faster, or would the extra time spent removing items be more impactful?

I understand the answer to this may depend upon certain details such as how many total lookups are done against the dictionary, the size of the key, and the size of the object, I will try to provide these below, but is there a general answer to this? Is it unnecessary to try and improve performance in this way, or are there cases where this would be a good idea?

Key is variable length string, either 6 characters or ~20 characters. Total lookups is completely up in the air, I may have to only check 50x or so or I may have to look 10K times completely independent of the size of the dictionary, i.e. dictionary may have 50 items and I may do 10K lookups, or I may have 10K items and only do 50 lookups.

One additional note is that if I do remove items from the dictionary and I am ever left with an empty dictionary I can then signal to a waiting thread to no longer wait for me while I process the remaining items (involves parsing through a long text file while looking up items in the dictionary to determine what to do with the parsed data).

like image 643
regis617 Avatar asked Apr 09 '15 15:04

regis617


1 Answers

Dictionary lookups are essentially O(1). Removing items from the dictionary will have a tiny (if any) impact on lookup speed.

In the end, it's very likely that removing items will be slower than just leaving them in.

The only reason I'd suggest removing items would be if you need to reduce your memory footprint.

like image 191
Jon Tirjan Avatar answered Sep 19 '22 13:09

Jon Tirjan