在我多年的编程生涯中,给我留下的印象是,将方法调用中的值存储到变量中,然后重复访问该变量比仅对方法进行后续调用要快得多。
例如,我有以下代码,它接受一个Integer
变量,将 a 附加String
到它,然后返回结果。
我的期望是多次访问先前声明的变量比随后调用此方法要快得多,该方法处理Integer
,但是我的结果却完全相反。
100 Test, 100 Test, 100 Test, 100 Test
Stroing in variable: 0.001
100 Test, 100 Test, 100 Test, 100 Test
Calling function on each instance: 0.0005
那么为什么多次调用一个函数似乎比只调用一个函数,然后多次访问内存要快呢?
Module Module1
Sub Main()
Dim TestInteger As Integer = 100
Dim TestString As String = ReturnString(TestInteger)
Dim StartTime As DateTime = New DateTime()
Dim EndTime As DateTime = New DateTime()
StartTime = DateTime.Now
Console.WriteLine("{0}, {1}, {2}, {3}", TestString, TestString, TestString, TestString)
EndTime = DateTime.Now
Console.WriteLine("Storing in variable: {0}" & Environment.NewLine, EndTime.Subtract(StartTime).TotalSeconds)
StartTime = DateTime.Now
Console.WriteLine("{0}, {1}, {2}, {3}", ReturnString(TestInteger), ReturnString(TestInteger), ReturnString(TestInteger), ReturnString(TestInteger))
EndTime = DateTime.Now
Console.WriteLine("Calling function on each instance: {0}", EndTime.Subtract(StartTime).TotalSeconds)
Console.Read()
End Sub
Function ReturnString(ByVal Int As Integer)
Dim MyString As String = Int.ToString
MyString = MyString & " Test"
Return MyString
End Function
End Module