How to speed up string comparisons in an array with a for loop?

151 views Asked by At

I am developing a C# program using Visual Studio 2013 that will compare two text files. There are two TextBoxes (dataTextOne and dataTextTwo) that contain the data from each file. There is a button (findNextLineButton) that checks for the next non-matching line between the two textboxes. Here is the code that runs when findNextLineButton is clicked.

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.");
}

The problem with this code is that it is running incredibly slowly, where i is only increasing by about 50 each second. So far the files I have been using have no more than 3 characters per line, and no special symbols.

How can I speed up this process?

1

There are 1 answers

0
coder_K On

Thanks to some helpful users, I've fixed this one.

To fix this, you simply need to copy the lines of the TextBox to an array. That way, instead of accessing the entire TextBox every execution of the for loop, you're only accessing the raw string data, which is all that is necessary in this case.