Hashtable fast when adding data. Dictionary fast when data is called frequently.
Dictionary<k,v> is generic, and when K or V is a value type, it is much faster than Hashtable.
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespacewindowsformsapp1{ Public classStudent {Private string_name; Private int_age; Public stringName {Get= _name;Set= = _name =value;} Public intAge {Get= _age;Set= = _age =value;} }}
Private voidButton1_Click (Objectsender, EventArgs e) {Stopwatch SW=NewStopwatch (); Hashtable Hashtable=NewHashtable (); Dictionary<int, student> dict =Newdictionary<int, student>(); intCountnum =1000000; Sw. Start (); for(inti =0; i < Countnum; i++) {Student s=NewStudent (); S.name="N"+i.tostring (); S.age=i; Hashtable. ADD (i, s); } SW. Stop (); Console.WriteLine (SW. Elapsedmilliseconds); //Output: 817SW. Restart (); for(inti =0; i < Countnum; i++) {Student s=NewStudent (); S.name="N"+i.tostring (); S.age=i; Dict. ADD (i, s); } SW. Stop (); Console.WriteLine (SW. Elapsedmilliseconds); //Output: 859SW. Restart (); for(inti =0; i < Countnum; i++) {hashtable. ContainsKey (i); Student S1=(Student) hashtable[i]; stringSTR1 =S1. Name; } SW. Stop (); Console.WriteLine (SW. Elapsedmilliseconds); //Output: 137SW. Restart (); for(inti =0; i < Countnum; i++) {Dict. ContainsKey (i); stringStr=Dict[i]. Name; } SW. Stop (); Console.WriteLine (SW. Elapsedmilliseconds); //Output: Wuyi }
C # Hash table (HashTable) and dictionary comparison