why foreach is faster than for loop while reading richtextbox lines

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

提交回复
热议问题