Imports System
Imports System.Diagnostics
Imports System.Collections.Generic

Public Class Test
    Public Shared Sub Main()
        Dim abHeader As Byte() = New Byte() {255, 127, 0, 0}
        Dim Format As String = "{0,-24}: {1}" & Environment.NewLine & "{2,-24}: {3}"
        Dim sw As New Stopwatch
        Dim r As New Random

        sw.Restart()
        Dim Result1 As Long = Method1(abHeader)
        sw.Stop()
        Dim Time1 As TimeSpan = sw.Elapsed

        'sw.Restart()
        'Dim Result2 As Long = Method2(abHeader)
        'sw.Stop()
        'Dim Time2 As TimeSpan = sw.Elapsed

        sw.Restart()
        Dim Result3 As Long = Method3(abHeader)
        sw.Stop()
        Dim Time3 As TimeSpan = sw.Elapsed

        Console.WriteLine(Format, "Bitwise Or", Result1, "Compile time", Time1)

        Dim ExecutionTimes1 As New List(Of Long)
        For x As Integer = 1 To 1000000
            abHeader = New Byte(0 To 3) {r.Next(0, 255), r.Next(0, 255), r.Next(0, 255), r.Next(0, 255)}
            sw.Restart()
            Dim Result As Long = Method1(abHeader)
            sw.Stop()
            ExecutionTimes1.Add(sw.Elapsed.Ticks)
        Next
        Console.WriteLine("{0,-24}: {1}", "1M iterations avg.", TimeSpan.FromTicks(GetAverage(ExecutionTimes1)))
        Console.WriteLine()

        Console.WriteLine(Format, "Convert.ToInt64()", "<CAST ERROR>", "Compile time", "???")
        Console.WriteLine()

        Console.WriteLine(Format, "BitConverter.ToInt32()", Result3, "Compile time", Time3)
        
        Dim ExecutionTimes3 As New List(Of Long)
        For x As Integer = 1 To 1000000
            abHeader = New Byte(0 To 3) {r.Next(0, 255), r.Next(0, 255), r.Next(0, 255), r.Next(0, 255)}
            sw.Restart()
            Dim Result As Long = Method3(abHeader)
            sw.Stop()
            ExecutionTimes3.Add(sw.Elapsed.Ticks)
        Next
        Console.WriteLine("{0,-24}: {1}", "1M iterations avg.", TimeSpan.FromTicks(GetAverage(ExecutionTimes3)))
    End Sub

    Public Shared Function Method1(ByVal Array As Byte()) As Long
        'NOTE: Indexes reversed due to different compiler endianness.'
        Return (CLng(Array(3)) << 24) Or (CLng(Array(2)) << 16) Or (CLng(Array(1)) << 8) Or (CLng(Array(0)))
    End Function

    Public Shared Function Method2(ByVal Array As Byte()) As Long
        Return Convert.ToInt64(Array)
    End Function

    Public Shared Function Method3(ByVal Array As Byte()) As Long
        Return CLng(BitConverter.ToInt32(Array, 0))
    End Function

    Public Shared Function GetAverage(ByVal List As List(Of Long)) As Long
        Dim ReturnValue As Long = 0
        For Each Value As Long In List
            ReturnValue += Value
        Next
        Return ReturnValue / List.Count
    End Function
End Class