在VB 2008中,为什么短路的操作需要比整数更长的时间?

Ste*_*GSD 3 optimization unsigned short visual-studio-2008

在这个例子中:

Sub Button1_Click(sender As Object, ByVal e As EventArgs) Handles Button1.Click
    Dim stopwatch1, stopwatch2 As New Stopwatch : Dim EndLoop As ULong = 10000

    stopwatch1.Start()
    For cnt As ULong = 1 To EndLoop
        Dim Number1 As UInt32
        For Number1 = 1 To 20000
            Dim Number2 As UInt32 = 0
            Number2 += 1
        Next
    Next
    stopwatch1.Stop()

    stopwatch2.Start()
    For cnt As ULong = 1 To EndLoop
        Dim Number1 As UShort
        For Number1 = 1 To 20000
            Dim Number2 As UShort = 0
            Number2 += 1
        Next
    Next
    stopwatch2.Stop()

    Label1.Text = "UInt32: " & stopwatch1.ElapsedMilliseconds
    Label2.Text = "UShort: " & stopwatch2.ElapsedMilliseconds
End Sub
Run Code Online (Sandbox Code Playgroud)

对于UInt32循环,我一直得到大约950毫秒,对于UShort循环,大约需要1900毫秒.如果我将UShort更改为Short,我也会得到大约1900 ms.

另外,我可以将第二个循环更改为:

stopwatch2.Start()
For cnt As ULong = 1 To EndLoop
    Dim Number1 As Integer
    For Number1 = 1 To 20000
        Dim Number2 As Integer = 0
        Number2 += 1
    Next
Next
stopwatch2.Stop()
Run Code Online (Sandbox Code Playgroud)

整数循环将始终为660 ms,而UInt32循环则为950 ms.

与Short,UShort和UInt32相比,Integers使用的数据类型更快吗?如果是这样,为什么?

Avi*_* P. 12

我敢打赌这是因为你的机器上的自然字大小是32位,而16位操作实际上会给系统带来更大的压力来削减和屏蔽这些位.

如果您在64位处理器上进行测试,Int64的结果可能比Int32更好...

此外,在.NET中,所有整数(最多32位)算术都会自动升级int,因此当您将结果分配回short变量时,您将导致额外的转换步骤.同样适用于uint.

  • 现在我真的是1337 :) (2认同)