开发者

In VB 2008, why does manipulation of shorts take longer than integers?

In this example:

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: " & st开发者_Go百科opwatch2.ElapsedMilliseconds
End Sub

I consistently get about 950 ms for the UInt32 loop, and about 1900 ms for the UShort loop. I get about 1900 ms as well if I changed the UShort to a Short.

Additionally, I can change the second loop to:

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

And the integer loop will be consistently 660 ms, compared to 950 ms for the UInt32 loop.

Are Integers the faster data type to use compared to Short, UShort and UInt32? If so, why?


I would bet it's because the natural word size on your machine is 32 bit, and doing 16 bit operations actually puts more strain on the system to cut and mask the bits.

If you'd test on a 64 bit processor, you might get better results for Int64 than for Int32...

Also, in .NET all integer (up to 32bit) arithmetics is automatically upcasted to int, so when you're assigning the result back to a short variable, you're causing an extra casting step. Same goes for uint.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜