why foreach is faster than for loop while reading richtextbox lines

前端 未结 5 2000
忘掉有多难
忘掉有多难 2020-12-21 00:49

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(in         


        
相关标签:
5条回答
  • 2020-12-21 01:11

    Probably because finding the next line in the textbox takes time. When you use random-access by indexing in the first case, it must find that line from scratch. When the iteration is done internally by foreach, it can retain state and quickly find the next line.

    This should make the first case run in O(n^2) time, while the second runs in O(n).

    0 讨论(0)
  • 2020-12-21 01:19

    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 :)

    0 讨论(0)
  • 2020-12-21 01:19

    Could it be that each line is being copied to a new string variable (str) on each loop? I'm guissing here, but you could probably verify 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;
    }
    
    0 讨论(0)
  • 2020-12-21 01:19

    .NET Reflector is very useful to determine why you're seeing performance you don't expect.

    Give it a try to look at the Lines get accessor to see what it actually does each time you access it.

    0 讨论(0)
  • 2020-12-21 01:25

    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.

    0 讨论(0)
提交回复
热议问题