views:

104

answers:

1

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: " & stopwatch2.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?

+11  A: 

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.

Aviad P.
I think you are correct. I'm running on a quad core on Win 7 64 bit.I changed the program to compile for x86 and it ran the Int32 loop in about 250 ms. I made the second loop Int64, and it compiled at about 650 ms on both x86 and x64.The only difference between changing from x86 to x64 was it made the Int32 operation take longer at about 660 ms compared to 250ms on x86. So knowing that I think you're correct because I bet it is doing the same thing on x86 to Int16, as x64 does to Int32.
CowKingDeluxe
Glad I provided some insight, if you'd check you might find my last paragraph is also correct :)
Aviad P.
Yeah I edited my comment after looking at it more.
CowKingDeluxe
Now I'm truly 1337 :)
Aviad P.
Do you want to get more upvotes? :)
SLaks
Haha i'm at the rep cap for today, upvote as much as you like :)
Aviad P.