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

前端 未结 9 949
我在风中等你
我在风中等你 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:31

    They are two completely different things, CStr is an overloaded function that converts the data within certain types into a string while ToString calls a method that all .net objects have and which you can override but which by default contains the name of the object. ToString will only return the data of a type if it has been overridden to do so.

    0 讨论(0)
  • 2021-01-11 15:33

    One BIG difference between CStr as ToString is handling of Enum variables.

    CStr returns the underlying number e.g. "2" and ToString returns the Enum name e.g. "LeftToRight"

    0 讨论(0)
  • 2021-01-11 15:36

    I tried to time the following two subroutines (forgive my variable naming):

     For i As Integer = 1 To 1000
            For j As Integer = 1 To 65536
                eee = aaa.ToString()
                eee = bbb.ToString()
                eee = ccc.ToString()
                eee = ffffd.ToString()
                eee = Nothing
            Next
     Next
    

    and

        For i As Integer = 1 To 1000
            For j As Integer = 1 To 65536
                eee = CStr(aaa)
                eee = CStr(bbb)
                eee = CStr(ccc)
                eee = CStr(ffffd)
                eee = Nothing
            Next
        Next
    

    where

        Dim aaa As Integer = 1233
        Dim bbb As Single = 445.234234234
        Dim ccc As Double = 234234.234457634
        Dim ffffd As Decimal = 1231.3466734523424
        Dim eee As String = Nothing
    

    the ToString() loop takes 62 seconds and the CStr() loop takes 64 seconds. It is really not a huge impact in my opinion, if you are only dealing with numbers. I disabled any compiler optimization during the timing process.

    0 讨论(0)
  • 2021-01-11 15:39

    CStr(object) is a cast (equivalent to (string)object in C#) and will throw esxception if given a null obejct or an object that cannot be casted to string. However .ToString() will work on any type of object (since it implemented in the Object class) and if not overridden by the current class will return the base ToString() method. In your case you must override ToString() method in your ID_TYPE class and return the string you need.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-11 15:47

    Late answer, but no one else bothered to check or cite the Visual Basic documentation, and it recommends the opposite of what most of these answers do. This is straight from the Microsoft documentation:

    As a rule, you should use the Visual Basic type conversion functions in preference to the .NET Framework methods such as ToString(), either on the Convert class or on an individual type structure or class. The Visual Basic functions are designed for optimal interaction with Visual Basic code, and they also make your source code shorter and easier to read.

    That said, sometimes there are differences between what CStr and ToString will return, so performance and readability aren't the only considerations. There is an excellent answer on another question that describes when and why this is the case. Reproduced here:

    The ToString method is a standard public method that returns a String. It is a method that is defined by the base Object type as overrideable. Each class can, therefore, override that method to return anything that it wants. It is quite common for classes to override the ToString method to make it return a nice human-readable description of the object.

    CStr, on the other hand, is a casting operator. It is shorthand for CType(x, String). The casting operator, like many other operators, can be overridden by any class. Normally, though, you want casting operations to return the closest representation of the actual value of the original object, rather than a descriptive string.

    It is not unusual then, that you may want ToString to return a different result than CStr. In the case of an enum, each member is essentially an Integer, so CStr on an enum member works the same as CStr on an integer. That is what you would expect. However, ToString has been overridden to return the more human readable version of the value. That is also what you would expect.

    So, in summary:

    When you want the closest string representation of the actual value of the original object, you should use CStr(). When you want the (potentially) customized, human-readable version of the value, you should use .ToString.

    0 讨论(0)
提交回复
热议问题