why foreach is faster than for loop while reading richtextbox lines

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

提交回复
热议问题