【发布时间】:2016-04-29 14:45:19
【问题描述】:
我正在使用 Visual Studio 2013 开发一个 C# 程序,它将比较两个文本文件。
有两个文本框(dataTextOne 和 dataTextTwo)包含来自每个文件的数据。有一个按钮 (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