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?
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With