为什么在阅读富文本框行时

为什么在阅读富文本框行时

本文介绍了为什么在阅读富文本框行时 foreach 比 for 循环快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从RichTextBox中逐行读取数据有两种方式

There are two ways to read data from RichTextBox line by line

1 ) 使用 for 循环遍历 RichtextBox 的行

1 ) use a for loop to loop through lines of a richtextBox

String s=String.Empty;
for(int i=0;i<richtextbox.lines.length;i++)
 {
     s=richTextBox.Lines[i]
 }

2 ) 使用 foreach 循环枚举richTextBox.Lines 集合

2 ) use a foreach loop to enumerate richTextBox.Lines collection

   String s=String.Empty;
   foreach(string str in txtText.Lines)
    {
       s=str;
    }

当我们使用 foreach 循环为 Richtextbox 枚举数组集合时,性能有很大差异.

There is a huge difference in performance when we use foreach loop to enumerate array collection for richtextbox.

我尝试了 15000 行.for 循环需要 8 分钟才能循环到 15000 行.而 foreach 只用了几分之一秒来枚举它.

I tried with 15000 lines.for loop took 8 minutes to just loop down to 15000 lines.while foreach took fraction of a second to enumerate it.

为什么会出现这种行为?

Why is this behaviour there?

推荐答案

正如 Mehrdad 所指出的,访问 Lines 属性需要很长时间.在这里你需要小心——你现在在每次迭代中两次访问它:

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++)
{
}

仍然在每次迭代中访问Lines以查看您是否已完成!

you're still accessing Lines on every iteration to see if you've finished!

如果你不想foreach,你可以只获取Lines一次:

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];
}

我个人更喜欢 foreach 除非你真的需要索引 :)

Personally I prefer the foreach unless you really need the index though :)

这篇关于为什么在阅读富文本框行时 foreach 比 for 循环快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 05:44