Tuesday, July 15, 2014

Use "Dictionary" instead of "Hashtable" – Performance Tips for Asp.Net

Tip 6. Use Dictionary instead of Hashtable

Hashtable has less performance than Dictionary because of Boxing and Unboxing. Dictionary is strongly typed key/value pair – Dictionary(Of TKey, TValue). Comparing both as following:

        Dim objDictionary As New Dictionary(Of String, String)
        Dim objHashtable As New Hashtable

        Dim sw As New Stopwatch
        sw.Start()

        For index = 1 To 1000000 Step 1
            Dim str As String = index.ToString & "i"
            objDictionary.Add(str, "Mitesh")
        Next

        Response.Write("<br>Dictionary Add time: " _
                       & sw.ElapsedMilliseconds.ToString())
        sw.Stop()
        sw = Nothing


        sw = New Stopwatch
        sw.Start()

        For index = 1 To 1000000 Step 1
            Dim str As String = index.ToString & "i"
            objHashtable.Add(str, "Mitesh")
        Next

        Response.Write("<br>Hashtable Add time: " _
                       & sw.ElapsedMilliseconds.ToString())
        sw.Stop()
        sw = Nothing


        sw = New Stopwatch
        sw.Start()

        For Each s As String In objDictionary.Keys

        Next

        Response.Write("<br>Dictionary Loop time: " _
                       & sw.ElapsedMilliseconds.ToString())
        sw.Stop()
        sw = Nothing


        sw = New Stopwatch
        sw.Start()

        For Each s As String In objHashtable.Keys

        Next

        Response.Write("<br>Hashtable Loop time: " _
                       & sw.ElapsedMilliseconds.ToString())
        sw.Stop()
        sw = Nothing


Result will be :

Dictionary Add time: 278 ms
Hashtable Add time: 536 ms
Dictionary Loop time: 8 ms
Hashtable Loop time: 49 ms



There are other dictionary collections available like:

ConcurrentDictionary(Of TKey, TValue)
SortedDictionary(Of TKey, TValue)
ReadOnlyDictionary(Of TKey, TValue)
HybridDictionary
ListDictionary
OrderedDictionary
StringDictionary


No comments:

Post a Comment

React-select is very slow on larger list - Found solution - using react-window

 I had more than 4000 items in searchable dropdownlist. I have used react-select but it was very slow. finally I found complete solution to ...