[ACCEPTED]-Which is more efficient Cstr(value) or value.ToString()-casting
From here (couldn't say it any better):
CStr 11 is a keyword, whereas ToString is a function 10 (method). CStr is compiled inline and 9 it creates code depending on the type 8 of the passed object. It's mainly there 7 for people being used to it from previous 6 VB versions. I haven't used CStr in .Net 5 anymore (because it's not obvious what 4 it does in which situations and it's also 3 not very well documented).
The difference 2 depends on which ToString function you 1 use. Every type can have it's own implementation.
For readability sake, if I were in the need 15 to write code in VB.NET (I am a C# programmer), I 14 would avoid the VB specific keywords/functions 13 as much as possible. By using .NET classes 12 and methods only, your code will be more 11 understandable by people used to develop 10 in other .NET languages. Not to mention 9 that these functions are there mainly for 8 compatibility with VB6 and they look a bit 7 out of place compared to the .NET way of 6 doing things.
Of course there may be reasonable 5 exceptions, sometimes VB.NET really makes 4 very easy to do certain tasks and it can 3 be convenient to take advantage of this; but 2 as a genereal rule I would not use any VB.NET 1 specific function.
One BIG difference between CStr as ToString 3 is handling of Enum variables.
CStr returns 2 the underlying number e.g. "2" and ToString 1 returns the Enum name e.g. "LeftToRight"
Late answer, but no one else bothered to 42 check or cite the Visual Basic documentation, and 41 it recommends the opposite of what most 40 of these answers do. This is straight from 39 the Microsoft documentation:
As a rule, you should use the Visual 38 Basic type conversion functions in preference 37 to the .NET Framework methods such as ToString(), either 36 on the Convert class or on an individual 35 type structure or class. The Visual Basic 34 functions are designed for optimal interaction 33 with Visual Basic code, and they also make 32 your source code shorter and easier to read.
That 31 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 30 question that describes when and why this 29 is the case. Reproduced here:
The ToString 28 method is a standard public method that 27 returns a String. It is a method that is 26 defined by the base Object type as overrideable. Each 25 class can, therefore, override that method 24 to return anything that it wants. It is 23 quite common for classes to override the 22 ToString method to make it return a nice 21 human-readable description of the object.
CStr, on 20 the other hand, is a casting operator. It 19 is shorthand for CType(x, String). The casting 18 operator, like many other operators, can 17 be overridden by any class. Normally, though, you 16 want casting operations to return the closest 15 representation of the actual value of the 14 original object, rather than a descriptive 13 string.
It is not unusual then, that you 12 may want ToString to return a different 11 result than CStr. In the case of an enum, each 10 member is essentially an Integer, so CStr 9 on an enum member works the same as CStr 8 on an integer. That is what you would expect. However, ToString 7 has been overridden to return the more human 6 readable version of the value. That is also 5 what you would expect.
So, in summary:
When you want the 4 closest string representation of the actual 3 value of the original object, you should 2 use CStr()
. When you want the (potentially) customized, human-readable 1 version of the value, you should use .ToString
.
Here is the code from the above test, but 8 redone with System.Diagnostics.Stopwatch, and 7 removing the Console.write bottleneck.
It 6 turns out directcasting is fastest(as well 5 it should be - it isn't doing anything in 4 this case. However its a trivialised example 3 because its rare you would want to convert 2 a string to a string. Converting Module 1 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
They are two completely different things, CStr 8 is an overloaded function that converts 7 the data within certain types into a string 6 while ToString calls a method that all .net 5 objects have and which you can override 4 but which by default contains the name of 3 the object. ToString will only return the 2 data of a type if it has been overridden 1 to do so.
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 3 makes it certain that CStr
is the fastest, then 2 goes DirectCast
and finally ToString
with highes performance 1 cost.
I tried to time the following two subroutines 6 (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 = ddd.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(ddd)
eee = Nothing
Next
Next
where
Dim aaa As Integer = 1233
Dim bbb As Single = 445.234234234
Dim ccc As Double = 234234.234457634
Dim ddd As Decimal = 1231.3466734523424
Dim eee As String = Nothing
the 5 ToString()
loop takes 62 seconds and the CStr()
loop takes 4 64 seconds. It is really not a huge impact 3 in my opinion, if you are only dealing with 2 numbers. I disabled any compiler optimization 1 during the timing process.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.