Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding to to a C# .NET Dictionary efficiently

Tags:

c#

.net

I am generating zillions of < string, double > pairs and storing each one in a .NET Dictionary if the string key is not already in use.

Efficiency-wise, is it better to do this ?

    try { Dict.Add(key, val); }  catch (ArgumentException) {} //blind attempt

or this ?

    if (!Dict.ContainsKey(key)) { Dict.Add(key, val); }       //smart attempt

The blind attempt triggers exceptions on dup keys; the smart attempt taps the Dictionary index twice - once to check, then again to add. (In my particular case there are dup keys around 10% of the time.)

Does anyone know offhand if one method should be preferred over the other?

like image 710
tpascale Avatar asked Dec 30 '25 17:12

tpascale


2 Answers

Exceptions in general are costly:

When a member throws an exception, its performance can be orders of magnitude slower.

That said, as Andrew Barber pointed out, this depends on what "zillions" is and how often you expect collisions to occur.

While you'd have to measure your performance to know for sure, I'd personally likely go for the check over waiting for an exception especially if you're not actually doing anything to handle the exception and are just planning to swallow it.

like image 71
Adam Lear Avatar answered Jan 01 '26 07:01

Adam Lear


Exceptions are generally more expensive than "doing it in a way that doesn't cause an exception". If you don't care about which value is included in the dictionary, you could do the following to avoid the double-check and the exception

Dict[key] = val;
like image 38
CodeNaked Avatar answered Jan 01 '26 08:01

CodeNaked



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!