Asc, AscW, and more (speed comparison)
I was curious about the relative speeds of character to integer conversions, so I did some benchmarking. I got these results:
Char.GetNumericValue("x"c) -- 4391 ms
Asc("x"c) -- 1797 ms
AscW("x"c) -- 734 ms
System.Convert.ToInt32("x"c) -- 532 ms
System.Convert.ToInt16("x"c) -- 671 ms
System.Convert.ToByte("x"c) -- 688 ms
MyAsc("x"c) -- 2281 ms
In order to see this yourself, insert this into a function:
VB Code:
Dim iTick As Integer
Dim iIterations As Integer = 100000000
Dim i As Integer
iTick = Environment.TickCount
For i = 0 To iIterations
Char.GetNumericValue("x"c)
Next
Console.WriteLine("Char.GetNumericValue(""x""c) -- {0} ms", Environment.TickCount - iTick)
iTick = Environment.TickCount
For i = 0 To iIterations
Asc("x"c)
Next
Console.WriteLine("Asc(""x""c) -- {0} ms", Environment.TickCount - iTick)
iTick = Environment.TickCount
For i = 0 To iIterations
AscW("x"c)
Next
Console.WriteLine("AscW(""x""c) -- {0} ms", Environment.TickCount - iTick)
iTick = Environment.TickCount
For i = 0 To iIterations
System.Convert.ToInt32("x"c)
Next
Console.WriteLine("System.Convert.ToInt32(""x""c) -- {0} ms", Environment.TickCount - iTick)
iTick = Environment.TickCount
For i = 0 To iIterations
System.Convert.ToInt16("x"c)
Next
Console.WriteLine("System.Convert.ToInt16(""x""c) -- {0} ms", Environment.TickCount - iTick)
iTick = Environment.TickCount
For i = 0 To iIterations
System.Convert.ToByte("x"c)
Next
Console.WriteLine("System.Convert.ToByte(""x""c) -- {0} ms", Environment.TickCount - iTick)
iTick = Environment.TickCount
For i = 0 To iIterations
MyAsc("x"c)
Next
Console.WriteLine("MyAsc(""x""c) -- {0} ms", Environment.TickCount - iTick)
MyAsc is included below simply to demonstrate that encapsulating the fastest method above in a function is not a good solution:
VB Code:
Private Function MyAsc(ByVal c As Char) As Integer
Return System.Convert.ToInt32(c)
End Function