Sometimes you want to create a unique lists, this can be done in various ways but since .NET3.5 a new method called HASHSET was created
Hash Set on MSDN: http://msdn.microsoft.com/en-us/library/bb359438.aspx
Some code I can across recently used SortedList and I wanted to see how this compared to HashSet.
So I set about testing a simple sting write and read 50,000; code below
SortedList
private static void RunSortedList() { SortedList SortedString = new SortedList (); // Sorted List WRITE TEST var SLWStart = DateTime.Now; for (int i = 1; i < 50000; i++) { SortedString.Add(i.ToString(), i.ToString()); } var SLWStop = DateTime.Now; var SLWT = SLWStop - SLWStart; Console.WriteLine(" Sorted List Write Diff : " + SLWT.Ticks); /// SORTED LIST READ TEST var SLRStart = DateTime.Now; foreach (var s in SortedString) { var mystr = s.Value + " "; } var SLRStop = DateTime.Now; var SLRT = SLRStop - SLRStart; Console.WriteLine(" Sorted List Read Diff : " + SLRT.Ticks); }
HashSet
private static void RunHasSet() { HashSet HashString = new HashSet (); // Sorted List WRITE TEST var HSWStart = DateTime.Now; for (int i = 1; i < 50000; i++) { HashString.Add(i.ToString()); } var HSWStop = DateTime.Now; var HSWT = HSWStop - HSWStart; Console.WriteLine(" HastSet Write Diff : " + HSWT.Ticks); /// SORTED LIST READ TEST var HSRStart = DateTime.Now; foreach (var s in HashString) { var mystr = s + " "; } var HSRStop = DateTime.Now; var HSRT = HSRStop - HSRStart; Console.WriteLine(" HastSet Read Diff : " + HSRT.Ticks); }
And just for a comparison
List
private static void RunSortedList() { SortedList SortedString = new SortedList (); // Sorted List WRITE TEST var SLWStart = DateTime.Now; for (int i = 1; i < 50000; i++) { SortedString.Add(i.ToString(), i.ToString()); } var SLWStop = DateTime.Now; var SLWT = SLWStop - SLWStart; Console.WriteLine(" Sorted List Write Diff : " + SLWT.Ticks); /// SORTED LIST READ TEST var SLRStart = DateTime.Now; foreach (var s in SortedString) { var mystr = s.Value + " "; } var SLRStop = DateTime.Now; var SLRT = SLRStop - SLRStart; Console.WriteLine(" Sorted List Read Diff : " + SLRT.Ticks); }
This was run multiple times via a console
Collecion | Write | Read |
---|---|---|
HashSet | 90,009 | 20,002 |
SortedList | 4,780,478 | 70,007 |
List | 60,006 | 20,002 |
No comments:
Post a Comment
Comments are welcome, but are moderated and may take a wee while before shown.