Reputation: 2576
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?
Upvotes: 2
Views: 200
Reputation: 69392
As has been mentioned in the other answers, exception handling can be slow so I'd opt for the ContainsKey
check. However, from a design perspective, it's not good practice to use exceptions to control program flow. Generally, exceptions should be used for exceptional cases.
If you think that there's a chance a duplicate key could exist then use ContainsKey
. If the same key being used is something that hints at a major failure somewhere in the system an exception might make more sense (although you need to do something with it rather than just catching it).
Upvotes: 1
Reputation: 22323
Use a ConcurrentDictionary<string, double>
and use the TryAdd()
method MSDN
Upvotes: 3
Reputation: 41403
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;
Upvotes: 4
Reputation: 38777
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.
Upvotes: 5
Reputation: 34834
Exceptions are very expensive efficiency-wise and I would advocate the smart approach
over the blind attempt approach
. Avoid exceptions whenever possible.
Read the True Cost Of Exceptions in .NET for more information of how inefficient exceptions are.
Upvotes: 3