Tro*_*Elf 1 vb.net caching memoization
这是我遇到的问题的代码.这很简单,但我还在学习.我想缓存结果,因此函数返回比当前快几秒.此时它应该返回到4中的调用者,应该是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
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激.
是的,这称为备忘录.
您可以在此处阅读:http: //en.wikipedia.org/wiki/Memoization
visual basic中的一个简单实现如下:
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
Run Code Online (Sandbox Code Playgroud)