后续对象引用与后续方法调用

时间:2015-10-28 14:00:06

标签: vb.net memory-access

在我多年的编程中,我留下了将方法调用中的值存储到变量中的印象,然后重复访问该变量要比后续调用该方法快得多。

例如,我有以下代码,它采用Integer变量,向其添加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

0 个答案:

没有答案