C# : foreach loop much faster than normal for loop

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;
}

No comments:

Post a Comment