I have a scenario where-in I can use either NameValueCollection or IDictionary. But I would like to know which one will be better performance-wise.
-- Using NameValueCollection
NameValueCollection options()
{
NameValueCollection nc = new NameValueCollection();
nc = ....; //populate nc here
if(sorting)
//sort NameValueCollection nc here
return nc;
}
-- using IDictionary
IDictionary<string, string> options()
{
Dictionary<string, string> optionDictionary = new Dictionary<string, string>();
optionDictionary = ....; //populate
if(sorting)
return new SortedDictionary<string, string>(optionDictionary);
else
return optionDictionary;
}
-
These collection types are not exactly interchangeable: NameValueCollection respects the order in which items are added, allowing easy access via integer indexes. If you don't need that functionality, you shouldn't use a NameValueCollection as it doesn't come "for free".
Depending on the number of strings you're looking at, I would consider either Hashtable or IDictionary. Krzysztof Cwalina discusses the subtleties here: http://blogs.gotdotnet.com/kcwalina/archive/2004/08/06/210297.aspx.
Jason DeFontes : NameValueCollection also supports more than one value per key (needed for query strings, etc.). -
The other advantage of IDictionary is that it's not implementation specific unlike NameValueCollection.
-
I agree with fatcat and lomaxx (and up-voted for both answers). I would add that performance of collection types should most likely be the last consideration when choosing between collection types. Use the type that most fits your usage needs. If you are in a performance critical section of code (and most likely, you're not), then the only answer is to measure each case - don't believe the Interweb, believe the numbers.
0 comments:
Post a Comment