I ran two different benchmark tests to demonstrate different approaches for updating a WinForms TextBox. I built a simple form a rich text box. On separate runs, I filled the text box with text as shown below:
// The += approach:
richTextBox1.Text = string.Empty;
for (int i = 0; i < 1000; i++)
{
richTextBox1.Text += "Hello, World!\r\n";
}
// The StringBuilder approach:
richTextBox2.Text = string.Empty;
var builder = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
builder.AppendLine("Hello, World!\r\n");
richTextBox2.Text = builder.ToString();
}
The AppendText() approach
richTextBox3.Text = string.Empty;
for (int i = 0; i < 1000; i++)
{
richTextBox3.AppendText("Hello, World!");
}
And the results on my old machine?
- += Approach: 10.7470703 seconds.
- StringBuilder: 10.7353515 seconds.
- AppendText(): 0.7041015 seconds.
I ran another benchmark. I filled a text box with 10MB of dummy text, then used the three approaches to append "Hello, World!" to the text box.
And the results of this?
- += Approach: 11.7470703 seconds.
- StringBuilder: 12.0615235 seconds.
- AppendText(): 0.1142578 seconds.
Conclusion: It is much faster to append to a text box using AppendText() than to assign text using string concatenation or from an intermediate data store such as s StringBuilder. Also note that the update rate drops substantially (9 per second) when the text box contained 10MB of text. Depending on the circumstances, a form designer might use multi-threading and caching (via StringBuilder) of text in chunks to reduce the frequency of updates required in the text box.
Note that the .NET text box is a wrapper of the Win32 text box which doesn't use immutable strings, thus giving it this edge in appending performance.