Reputation: 7249
Which one is faster? Which one uses less memory?
Console.WriteLine("string1")
Console.WriteLine("string2")
Console.WriteLine("string3")
Console.WriteLine("stringNth")
or
StringBuilder output = new StringBuilder();
output.AppendLine("string1");
output.AppendLine("string2");
output.AppendLine("string3");
output.AppendLine("stringNth");
Console.WriteLine(output);
thanks,
Upvotes: 7
Views: 1966
Reputation: 543
Since this is a 7 year old question and answers here needed some more clarity adding my answer.
Console.WriteLine will be slower. But it will consume less memory. Second one will take more memory but it will be much much faster.
Some statistics: Writing 100,000 using Console.Writeline takes approx 30 seconds. Using String builder it takes less than a second.
If strings are small then memory won't be an issue and using second approach will be better.
Upvotes: 2
Reputation: 564333
The first.
The console class is going to buffer this to the standard output stream.
With the second option, you're trying to create your own buffer, then buffer that again.
Take it to an extreme - do this 10,000,000 times. Your StringBuilder would eventually eat up all of your memory, where the Console would just be spitting out output.
Upvotes: 10
Reputation: 1714
The best way to find out would be to time 10,000 iterations of each and see which is faster. I suspect that they will be almost identical in terms of performance.
Upvotes: -1