Reinventing The Wheel

Why you should minimise the amount of times you write to the GUI

Let's have a look at the timing differences between writing a large string to a TextBox, by creating it in a for loop, and writing the string to the GUI by appending text to the TextBox each time in the for loop.

To test this, I created a Windows Form similar to the following:

This is the code for the button click events:

private int numberOfIterations = 1000;
private void WriteToGuiManyTimesButton_Click(object sender, EventArgs e)
{
    TestTextBox.Text = string.Empty;
    DateTime startTime = DateTime.Now;
    for (int i = 0; i < numberOfIterations; i++)
    {
        TestTextBox.Text += "s";
    }
    DateTime endTime = DateTime.Now;
    TestLabel.Text = (endTime.Ticks - startTime.Ticks).ToString();
}

private void WriteToGuiOnceButton_Click(object sender, EventArgs e)
{
    TestTextBox.Text = string.Empty;
    DateTime startTime = DateTime.Now;
    string s = "";
    for (int i = 0; i < numberOfIterations; i++)
    {
        s += "s";
    }
    TestTextBox.Text = s;
    DateTime endTime = DateTime.Now;
    TestLabel.Text = (endTime.Ticks - startTime.Ticks).ToString();
}

Results

Here are the timing results for each button:

Button Time (ticks)
Write to GUI many times 1222285
Write to GUI once 9985

The Write to GUI once button was 1212300 ticks faster than the Write to GUI many times button.

As you can see preparing the string first, and then writing it to the GUI is much faster than writing part of the string to the GUI many times.

The lesson here is try to minimise the amount of times you write to the GUI.