It's official....Convert blows.
I ran a number of tests converting a double to an integer usingboth Convert & CType. I *ASSUMED* that CType would piggy-back ontop of Convert, and that performance would be identical.
I was 100% incorrect.
The code below produces the results:
CType Took: 0.2187528 seconds.
Convert Took: 12.187656 seconds.
Option Explicit On
Option Strict On
Module ConversionTest
Private Const STORED_VALUE As Double = 100000000
Sub Main()
TestCType()
TestConvert()
Console.ReadLine()
End Sub
Private Sub TestCType()
Dim l_Time As Long = 0
Dim l_Converted As Integer = 0
l_Time = DateTime.Now.Ticks
For l_LoopCounter As Integer = 0 To 100000000
l_Converted = CType(STORED_VALUE, Integer)
Next
l_Time = DateTime.Now.Ticks - l_Time
Console.WriteLine("Took " & (l_Time / 10000000) & "seconds.")
End Sub
Private Sub TestConvert()
Dim l_Time As Long = 0
Dim l_Converted As Integer = 0
l_Time = DateTime.Now.Ticks
For l_LoopCounter As Integer = 0 To 100000000
l_Converted = Convert.ToInt32(STORED_VALUE)
Next
l_Time = DateTime.Now.Ticks - l_Time
Console.WriteLine("Took " & (l_Time / 10000000) & "seconds.")
End Sub
End Module
The IL is VERY different. It appears as though the Convert iscreating a local copy of the Const variable per loop. Is thiscorrect? Does Convert take into account globalization? (Thatwould certainly explain the delay) If you change the conversionto act against the l_LoopCounter then the performance differencenarrows substantially, BUT Convert is still far behind.
It seems that in *ALL* cases, CType > Convert. (This *ALSO* holdstrue in C#.)
Thank you.
--------------------------------
From: Logan X
-----------------------
Posted by a user from .NET 247 (http://www.dotnet247.com/)
<Id>F4QPoBi5CkGScnFqZ4CGOw==</Id>