Saturday, 17 August 2013

C#: Why does .ToString() append text faster to an int converted to string?

C#: Why does .ToString() append text faster to an int converted to string?

This is from C# in a nutshell book
StringBuilder sb = new StringBuilder();
for(int i =0;i<50;i++)
sb.Append ( i+",");
//Outputs 0,1,2,3.............49,
However , it then says "the expression i + "," means that we are still
repeatedly concatenating strings, howver this only incurs a small
performance cost as strings are small"
Then it says that changing it to the lines below makes it faster
for(int i =0;i<50;i++) {
sb.Append(i.ToString());
sb.Append(",");
}
But why is that faster? Now we have an extra step where i is being
converted to a string? What is actually going under the hood here?There
isn't any more explanation in the rest of the chapter.

No comments:

Post a Comment