Search code examples
vb.netcachingmemoization

Want to make a cache


Here's the code for the problem I'm having. It's pretty simple but I'm still learning. I want to cache the result so the function returns a few seconds quicker than it currently is. At the moment it is returning to the caller in 4 when it should be 2.

Sub Main
    console.writeline(getmyresult(2)) 'takes a while'
    console.writeline(getmyresult(3)) 'takes a while'
    console.writeline(getmyresult(2)) 'Should be instant'
    console.writeline(getMyresult(3)) 'Should be instant'
End Sub


function getMyresult(X as interger) as integer
    dim Y as integer=LongCompute(X)
    return Y
end function


function LongCompute(X as integer) as integer
    system.threading.thread.sleep(1000)
    return x^2
end function

Any help would be greatly appreciated.


Solution

  • Yep, this is called memo-ization.

    You can read up on it here: http://en.wikipedia.org/wiki/Memoization

    A simple implementation in visual basic would look like:

    Dim dict As New Dictionary(Of Integer, Integer)
    
    Sub Main()
        console.writeline(getmyresult(2)) 'takes a while'
        console.writeline(getmyresult(3)) 'takes a while'
        console.writeline(getmyresult(2)) 'Should be instant'
        console.writeline(getMyresult(3)) 'Should be instant'
    End Sub
    
    Function getMyresult(ByVal X As Integer) As Integer
        If dict.ContainsKey(X) Then
            Return dict(X)
        Else
            Dim temp = LongCompute(X)
            dict.Add(X, temp)
            Return temp
        End If
    End Function
    
    Function LongCompute(ByVal X As Integer) As Integer
        System.Threading.Thread.Sleep(1000)
        Return x ^ 2
    End Function