Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why foreach is faster than for loop while reading richtextbox lines

Tags:

richtextbox

There are two ways to read data from RichTextBox line by line

1 ) use a for loop to loop through lines of a richtextBox

String s=String.Empty;
for(int i=0;i<richtextbox.lines.length;i++)
 {
     s=richTextBox.Lines[i]
 }

2 ) use a foreach loop to enumerate richTextBox.Lines collection

   String s=String.Empty;
   foreach(string str in txtText.Lines)
    {
       s=str;
    }

There is a huge difference in performance when we use foreach loop to enumerate array collection for richtextbox.

I tried with 15000 lines.for loop took 8 minutes to just loop down to 15000 lines.while foreach took fraction of a second to enumerate it.

Why is this behaviour there?

like image 475
Rohit Raghuvansi Avatar asked Jul 16 '09 10:07

Rohit Raghuvansi


2 Answers

As Mehrdad noted, accessing the Lines property takes a long time. You need to be careful here - you're accessing it twice in each iteration at the moment:

String s = String.Empty;
for (int i = 0; i < richTextBox.Lines.Length; i++)
{
    s = richTextBox.Lines[i];
}

Even if you remove the access in the body of the loop like this:

String s = String.Empty;
for (int i = 0; i < richTextBox.Lines.Length; i++)
{
}

you're still accessing Lines on every iteration to see if you've finished!

If you don't want to foreach, you can just fetch Lines once:

string[] lines = richTextBox.Lines;
for (int i = 0; i < lines.Length; i++)
{
    s = lines[i];
}

Personally I prefer the foreach unless you really need the index though :)

like image 185
Jon Skeet Avatar answered Oct 27 '22 22:10

Jon Skeet


I think the Lines property is recalculated every time you want to access it. Consequently, the foreach method performs the calculation only once, while every time your reference Lines[i] it's re-evaluating the whole thing. Try caching the result of Lines property and checking again:

String s = String.Empty;
var lines = richtextbox.Lines;
for(int i = 0; i < lines.Length; i++)
{
    s = lines[i];
}

By the way, your question makes an implicit assumption that foreach is always slower than for. This is not always true.

like image 41
mmx Avatar answered Oct 27 '22 22:10

mmx