Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IDictionary<string, string> or NameValueCollection

Tags:

c#

generics

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; } 
like image 457
Ujwala Khaire Avatar asked Mar 06 '09 01:03

Ujwala Khaire


2 Answers

These collection types are not exactly interchangeable: NameValueCollection allows access via integer indexes. If you don't need that functionality, you shouldn't use a NameValueCollection as indexing doesn't come "for free".

Depending on the number of strings you're looking at, I would consider either Hashtable<string, string> or IDictionary<string, string>. Krzysztof Cwalina discusses the subtleties here: http://blogs.gotdotnet.com/kcwalina/archive/2004/08/06/210297.aspx.

like image 133
Justin R. Avatar answered Sep 19 '22 20:09

Justin R.


The other advantage of IDictionary is that it's not implementation specific unlike NameValueCollection.

like image 23
lomaxx Avatar answered Sep 22 '22 20:09

lomaxx