如何使用for循环加速数组中的字符串比较?

时间:2015-06-09 03:03:43

标签: arrays for-loop optimization comparison

我正在使用Visual Studio 2013开发一个C#程序,它将比较两个文本文件。 有两个TextBox(dataTextOnedataTextTwo)包含每个文件的数据。有一个按钮(findNextLineButton),用于检查两个文本框之间的下一个不匹配的行。以下是单击findNextLineButton时运行的代码。

private void findNextLineButton_Click(object sender, EventArgs e)
{
    //set the starting point of the search to the lowest currently selected line of the two text boxes.
    int start = Math.Min(dataTextOne.GetLineFromCharIndex(dataTextOne.GetFirstCharIndexOfCurrentLine()), dataTextTwo.GetLineFromCharIndex(dataTextTwo.GetFirstCharIndexOfCurrentLine())) + 1;
    //set the ending point of the search to the length of the shortest text box.
    int length = Math.Min(dataTextOne.Lines.Length, dataTextTwo.Lines.Length);

    //loop through the lines of each textbox, stopping at the first point where the corresponding lines differ in value.
    for (int i = start; i < length; i++)
    {
        if (dataTextOne.Lines[i] != dataTextTwo.Lines[i])
        {
            //selects and scrolls to the non-matching text.
            dataTextOne.Focus();
            dataTextTwo.Focus();
            dataTextOne.SelectionStart = dataTextOne.GetFirstCharIndexFromLine(i);
            dataTextOne.SelectionLength = dataTextOne.Lines[i].Length;
            dataTextOne.ScrollToCaret();
            dataTextTwo.SelectionStart = dataTextTwo.GetFirstCharIndexFromLine(i);
            dataTextTwo.SelectionLength = dataTextTwo.Lines[i].Length;
            dataTextTwo.ScrollToCaret();
            return;
         }
    }

    //in the case that the method has not yet returned, informs the user that no ingcongruities were found.
    MessageBox.Show("Could not find incongruous line.");
}

这段代码的问题在于它的运行速度非常慢,我每秒只增加约50。到目前为止,我使用的文件每行不超过3个字符,没有特殊符号。

如何加快这个过程?

1 个答案:

答案 0 :(得分:1)

感谢一些有用的用户,我已经解决了这个问题。

要解决此问题,您只需将TextBox的行复制到数组即可。这样,每次执行for循环都不会访问整个TextBox,而只是访问原始字符串数据,这就是这种情况下所需的全部内容。