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

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

    For readability sake, if I were in the need to write code in VB.NET (I am a C# programmer), I would avoid the VB specific keywords/functions as much as possible. By using .NET classes and methods only, your code will be more understandable by people used to develop in other .NET languages. Not to mention that these functions are there mainly for compatibility with VB6 and they look a bit out of place compared to the .NET way of doing things.

    Of course there may be reasonable exceptions, sometimes VB.NET really makes very easy to do certain tasks and it can be convenient to take advantage of this; but as a genereal rule I would not use any VB.NET specific function.

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

    From here (couldn't say it any better):

    CStr is a keyword, whereas ToString is a function (method). CStr is compiled inline and it creates code depending on the type of the passed object. It's mainly there for people being used to it from previous VB versions. I haven't used CStr in .Net anymore (because it's not obvious what it does in which situations and it's also not very well documented).

    The difference depends on which ToString function you use. Every type can have it's own implementation.

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

    Here is the results of a little test I made:

    Module Module1
      Sub Main()
    
        Dim obj As Object = "asdfsdasdfsadfasdfasdfasdfsdasdfsadfasdfasdfdafsdfasd"
        Dim y = Now, z = Now
    
        y = Now
        For i = 0 To Short.MaxValue
          Console.WriteLine(obj.ToString)
        Next
        z = Now
        Dim time1 = z - y
    
        y = Now
        For i = 0 To Short.MaxValue
          Console.WriteLine(CStr(obj))
        Next
        z = Now
    
        Dim time2 = z - y
        y = Now
        For i = 0 To Short.MaxValue
          Console.WriteLine(DirectCast(obj, String))
        Next
        z = Now
    
        Dim time3 = z - y
    
        Console.WriteLine("obj.ToString took {0}.", time1)
        Console.WriteLine("CStr(obj) took {0}.", time2)
        Console.WriteLine("DirectCast(obj, String) took {0}.", time3)
        Console.Read()
      End Sub
    End Module
    

    Results:

    obj.ToString() took 00:00:06.9303964.
    CStr(obj) took 00:00:06.8763933.
    DirectCast(obj, String) took 00:00:06.8903941.
    

    Which makes it certain that CStr is the fastest, then goes DirectCast and finally ToString with highes performance cost.

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