Which is more efficient Cstr(value) or value.ToString()

前端 未结 9 1013
我在风中等你
我在风中等你 2021-01-11 14:56

I am wondering which is more efficient, using CStr() or object.toString(). The reason I ask this is because I though all that CStr() done was to invoke the .ToString() metho

9条回答
  •  情歌与酒
    2021-01-11 15:47

    Here is the code from the above test, but redone with System.Diagnostics.Stopwatch, and removing the Console.write bottleneck.

    It turns out directcasting is fastest(as well it should be - it isn't doing anything in this case. However its a trivialised example because its rare you would want to convert a string to a string. Converting Module Module1 Sub Main()

        Dim obj As Object = "asdfsdasdfsadfasdfasdfasdfsdasdfsadfasdfasdfdafsdfasd"
        Dim LL As New List(Of String), SWW As System.Diagnostics.Stopwatch
    
        LL.Clear()
    
        SWW = Stopwatch.StartNew()
        For i = 0 To Short.MaxValue
            LL.Add(obj.ToString)
        Next
        Console.WriteLine("obj.ToString took {0}.", SWW.ElapsedTicks)
    
        LL.Clear()
        SWW = Stopwatch.StartNew()
        For i = 0 To Short.MaxValue
            LL.Add(CStr(obj))
        Next
        Console.WriteLine("CStr(obj) took {0}.", SWW.ElapsedTicks)
    
        LL.Clear()
        SWW = Stopwatch.StartNew()
        For i = 0 To Short.MaxValue
            LL.Add(DirectCast(obj, String))
        Next
        Console.WriteLine("DirectCast(obj, String) took {0}.", SWW.ElapsedTicks)
    
    
    
    
    
        Console.WriteLine("---------------- Integer To String ----------- ")
    
        obj = 15522
    
        LL.Clear()
        SWW = Stopwatch.StartNew()
        For i = 0 To Short.MaxValue
            LL.Add(obj.ToString)
        Next
        Console.WriteLine("obj.ToString took {0}.", SWW.ElapsedTicks)
    
        LL.Clear()
        SWW = Stopwatch.StartNew()
        For i = 0 To Short.MaxValue
            LL.Add(CStr(obj))
        Next
        Console.WriteLine("CStr(obj) took {0}.", SWW.ElapsedTicks)
    
        LL.Clear()
        SWW = Stopwatch.StartNew()
        For i = 0 To Short.MaxValue
            Dim str As String = TryCast(obj, String)
            ' This obviously fails, as obj is not a string, which is why it is so fast.. str is then nothing
            LL.Add(str)
    
        Next
        Console.WriteLine("DirectCast(obj, String) took {0}.", SWW.ElapsedTicks)
    
        Console.Read()
    End Sub
    

    End Module

    My results:

    (string ) : ToString : 2288; CStr: 2275; DirectCast: 1586

    (integer) : ToString : 10526; CStr: 13184; TryCast: 982

提交回复
热议问题