Sunday, 18 August 2013

adding to to a C# .NET Dictionary efficiently

adding to to a C# .NET Dictionary efficiently

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?

No comments:

Post a Comment