3

在这个例子中:

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

UInt32 循环我一直得到大约 950 毫秒,UShort 循环大约 1900 毫秒。如果我将 UShort 更改为 Short,我也会得到大约 1900 毫秒。

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

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()

整数循环将始终为 660 毫秒,而 UInt32 循环为 950 毫秒。

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

4

1 回答 1

12

我敢打赌,这是因为您机器上的自然字长是 32 位,而执行 16 位操作实际上会给系统带来更大的压力来剪切和屏蔽这些位。

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

此外,在 .NET 中,所有整数(最多 32 位)算术都会自动向上转换为int,因此当您将结果分配回short变量时,会导致额外的转换步骤。uint 也是如此。

于 2009-12-31T20:42:38.850 回答