【问题标题】:How to speed up string comparisons in an array with a for loop?如何使用 for 循环加速数组中的字符串比较?
【发布时间】:2016-04-29 14:45:19
【问题描述】:

我正在使用 Visual Studio 2013 开发一个 C# 程序,它将比较两个文本文件。 有两个文本框(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 个字符,并且没有特殊符号。

我怎样才能加快这个过程?

【问题讨论】:

  • 如果这个问题用您正在使用的编程语言标记可能会有所帮助。我猜……C#?
  • 文本框是带有需要更新的事件和 UI 的复杂控件。为什么不只比较实际的数组而不是文本框?
  • 这里有一些可以改进的地方:1) 将文本框交互与 diff 逻辑分开,后者应该对纯字符串进行操作,2) 通过预先计算需要循环的行号来避免浪费计算通过。换句话说,实现一个方法int[] Diff(string corpus1, string corpus2),它接受两个多行字符串并返回您需要向用户突出显示的行号。然后使用此预先计算的信息进行突出显示。
  • en.wikipedia.org/wiki/Diff_utility 应该给你一个很好的起点。
  • 好吧,我不确定我是否具备创建行计算方法的字符串操作知识,但是我创建了两个字符串数组来循环遍历而不是遍历文本框行,并且速度大幅增加。谢谢你们的帮助,伙计们!

标签: arrays for-loop optimization comparison


【解决方案1】:

感谢一些乐于助人的用户,我已经修复了这个问题。

要解决这个问题,您只需将 TextBox 的行复制到一个数组中。这样,您不必在每次执行 for 循环时都访问整个 TextBox,而只是访问原始字符串数据,在这种情况下,这就是所有必要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-05
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多