[ACCEPTED]-why foreach is faster than for loop while reading richtextbox lines-richtextbox
As Mehrdad noted, accessing the Lines
property 9 takes a long time. You need to be careful 8 here - you're accessing it twice in each iteration 7 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 6 in the body of the loop like this:
String s = String.Empty;
for (int i = 0; i < richTextBox.Lines.Length; i++)
{
}
you're 5 still accessing Lines
on every iteration to see if 4 you've finished!
If you don't want to foreach
, you 3 can just fetch Lines
once:
string[] lines = richTextBox.Lines;
for (int i = 0; i < lines.Length; i++)
{
s = lines[i];
}
Personally I prefer 2 the foreach
unless you really need the index though 1 :)
I think the Lines
property is recalculated every 8 time you want to access it. Consequently, the 7 foreach
method performs the calculation only once, while 6 every time your reference Lines[i]
it's re-evaluating 5 the whole thing. Try caching the result 4 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 3 question makes an implicit assumption that 2 foreach
is always slower than for
. This is not always 1 true.
Probably because finding the next line in 7 the textbox takes time. When you use random-access 6 by indexing in the first case, it must find 5 that line from scratch. When the iteration 4 is done internally by foreach
, it can retain state 3 and quickly find the next line.
This should 2 make the first case run in O(n^2) time, while 1 the second runs in O(n).
Could it be that each line is being copied 3 to a new string variable (str) on each loop? I'm 2 guissing here, but you could probably verify 1 the theory with this code
String s = String.Empty;
for (int i = 0; i < richTextBox.Lines.Length; i++)
{
string str = richTextBox.Lines[i];
s = str;
}
.NET Reflector is very useful to determine why you're seeing 3 performance you don't expect.
Give it a try 2 to look at the Lines
get
accessor to see what it 1 actually does each time you access it.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.