VB.Net CType vs. Convert & C# Casting vs. Convert

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Logan X via .NET 247

    VB.Net CType vs. Convert & C# Casting vs. Convert

    It's official....Con vert 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.ReadLin e()
    End Sub

    Private Sub TestCType()
    Dim l_Time As Long = 0
    Dim l_Converted As Integer = 0

    l_Time = DateTime.Now.Ti cks
    For l_LoopCounter As Integer = 0 To 100000000
    l_Converted = CType(STORED_VA LUE, Integer)
    Next
    l_Time = DateTime.Now.Ti cks - l_Time
    Console.WriteLi ne("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.Ti cks
    For l_LoopCounter As Integer = 0 To 100000000
    l_Converted = Convert.ToInt32 (STORED_VALUE)
    Next
    l_Time = DateTime.Now.Ti cks - l_Time
    Console.WriteLi ne("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 differencenarro ws 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>F4QPoBi5CkG ScnFqZ4CGOw==</Id>
Working...