or objThatIsString.ToString() as it was pointed out in the aswers .. Faster not wiser ..
views:
1021answers:
6With C# which one is faster - System.Convert.ToString( objThatIsString) or (string)objThatIsString ?
The cast (string)obj
should be faster. The Convert class actually converts objects that are of different class and will be slower in this case.
I think that (string) objThatIsString
is faster because the Compiler will be able to do this conversion at compile time.
However, Jeff Atwood thinks that its not important after all (Coding Horror: The Sad Tragedy of Micro-Optimization Theater)
The direct cast doesn't have to do any checking except a runtime type check - I would expect that the cast is quicker.
You might also want to consider objThatIsString.ToString()
; since (for string
) this is just return this;
, it should be quick - certainly quicker than the Convert.ToString
. Then the race is between a runtime type-check and a virtual call; in reality, both are very, very quick.
The cast is faster.
The Convert.ToString
will eventually do a cast after some overhead. It actually does it in the form of attempting to cast it to IConvertible
, and then call the virtual method ToString
on it. So, it's the virtual call that does the actual casting to String
.
There's a saying "The numbers tell the tale". Which means that instead of assuming something you can also measure it!
So, wrap up a test app, run your tests and validate the results!
The true question could be: How do I measure which way is faster?
@thijs: Here's a quick test:
public class ToStringTest
{
private object mString = "hello world!";
Stopwatch sw = new Stopwatch();
private List<long> ConvertToStringTimes = new List<long>();
private List<long> ToStringTimes = new List<long>();
private List<long> CastToStringTimes = new List<long>();
public ToStringTest()
{
for (int i = 0; i < 100000; i++)
{
sw.Start();
ConvertToString();
sw.Stop();
ConvertToStringTimes.Add(sw.ElapsedTicks);
sw.Reset();
sw.Start();
ToString();
sw.Stop();
ToStringTimes.Add(sw.ElapsedTicks);
sw.Reset();
sw.Start();
CastToString();
sw.Stop();
CastToStringTimes.Add(sw.ElapsedTicks);
sw.Reset();
}
Console.WriteLine("Average elapsed ticks after converting {0} strings",ConvertToStringTimes.Count);
Console.WriteLine("ConvertToString: {0} ticks", ConvertToStringTimes.Average() );
Console.WriteLine("ToString: {0} ticks", ToStringTimes.Average());
Console.WriteLine("CastToString: {0} ticks", CastToStringTimes.Average());
}
private string ConvertToString()
{
return Convert.ToString(mString);
}
public override string ToString()
{
return mString.ToString();
}
public string CastToString()
{
return (string) mString;
}
}
Results in:
Average elapsed ticks after converting 100000 strings
ConvertToString: 611.97372 ticks
ToString: 586.51461 ticks
CastToString: 582.25266 ticks