Search results for 'Environment'. 1 post(s) found.

  1. 2007/09/25 How to speed up access to the RichTextBox Lines property
2007/09/25 15:03

How to speed up access to the RichTextBox Lines property


Using a foreach loop will be substantially faster than a for loop when accessing the items in a RichTextBox's Lines property. For example, the following code loads a RichTextBox with 1000 lines of text and accesses each line from the Lines property. On a 333 MHz Pentium II machine, the for-loop code (ForLoopButton_Click) takes ~25 seconds and the foreach code (ForEachLoopButton_Click) takes ~0.01 seconds.

...
private void Form1_Load(object sender, System.EventArgs e)
{
    Cursor.Current = Cursors.WaitCursor;

    StringBuilder Buffer = new StringBuilder("");

    for (int i = 1; i <= 1000; i++)
    {
        if (i > 1)
        {
            Buffer.Append(Environment.NewLine);
        }

        Buffer.Append("This is line number " + i.ToString());
    }

    TheRichTextBox.Text = Buffer.ToString();

    Cursor.Current = Cursors.Arrow;
}

private void ForLoopButton_Click(object sender, System.EventArgs e)
{
    Cursor.Current = Cursors.WaitCursor;
    int Len = 0;

    int Start = Environment.TickCount;

    for (int i = 0; i < TheRichTextBox.Lines.Length; i++)
    {
        Len += TheRichTextBox.Lines[i].Length;
    }

    int ElapsedTime = Environment.TickCount - Start;

    ResultsTextBox.Clear();

    ResultsTextBox.Text = "for loop\r\n\r\nElapsed time = " + ((double) ElapsedTime / (double) 1000.0).ToString() + " seconds\r\n\r\nResult = " + Len.ToString();

    Cursor.Current = Cursors.Arrow;
}

private void ForEachLoopButton_Click(object sender, System.EventArgs e)
{
    Cursor.Current = Cursors.WaitCursor;
    int Len = 0;

    int Start = Environment.TickCount;

    foreach (String Line in TheRichTextBox.Lines)
    {
        Len += Line.Length;
    }

    int ElapsedTime = Environment.TickCount - Start;

    ResultsTextBox.Clear();

    ResultsTextBox.Text = "foreach loop\r\n\r\nElapsed time = " + ((double) ElapsedTime / (double) 1000.0).ToString() + " seconds\r\n\r\nResult = " + Len.ToString();

    Cursor.Current = Cursors.Arrow;
}
...

Trackback 3 Comment 0

Trackback : Cannot send a trackbact to this post.

  1. Subject different money making ideas

    Tracked from moneyideas 2010/01/29 04:51 delete

    moneyideas

  2. Subject different money making ideas

    Tracked from moneyideas 2010/01/29 13:41 delete

    moneyideas

  3. Subject different money making ideas

    Tracked from moneyideas 2010/01/31 16:41 delete

    moneyideas