why foreach is faster than for loop while reading richtextbox lines

前端 未结 5 2013
忘掉有多难
忘掉有多难 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: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 :)

提交回复
热议问题