I tested the speed of i.ToString()
, i + ""
, Console.WriteLine(i+"")
and Console.WriteLine(i)
. (i
was an int
)
The results were the following:
i.ToString()
(149 ms) was faster than i + ""
(202 ms).
But when I used Console.WriteLine
Console.WriteLine(i + "")
(743 ms) was a lot faster than Console.WriteLine(i)
(927 ms, according to TextWriter source Console.WriteLine calls ToString()
internally).
Now my question is: Why is i + ""
faster in combination with Console.WriteLine()
?
When I looked at source code, I saw this:
i + ""
= String.Concat(object)
which call obj.ToString()
There is one more String.Concat(object)
. So it is slower.
1st way) With Console.WriteLine it is simple:
public static void WriteLine(String value)
{
Out.WriteLine(value);
}
https://referencesource.microsoft.com/#mscorlib/system/console.cs,5ac7c4fda643413b
Internaly it creates 1 buffer with value + '\r\n' and call .Write(char[], int, int)
only once.
2nd way) When you call it with int, it is different.
public virtual void WriteLine(int value) {
Write(value);
WriteLine();
}
https://referencesource.microsoft.com/#mscorlib/system/console.cs,82d5745bf4a5ecc6
That way it calls Write(char[], int, int)
twice. And it can be that slowdown but I can't tell for sure. It is only the hint, where the problem can be.
EDIT:
Additionaly the 2nd way, it calls int.ToString(IFormatProvider)
to get string representation of number where is another overhead that can slow it down a little because it can get the instance of that provider every time.
https://referencesource.microsoft.com/#mscorlib/system/globalization/numberformatinfo.cs,9c4284b5db21c23a