How to speed up comparing strings in an array with a for loop?

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 data from each file. There is a button ( findNextLineButton

) that checks for the next inconsistent line between two text fields. Here is the code that runs when the NextLineButton 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 incredibly slow where i only grows by about 50 per second. So far, the files I have used have at most 3 characters per line and no special characters.

How can this process be accelerated?

+3


source to share


1 answer


Thanks to some helpful users, I have fixed this.



To fix this, you just need to copy the lines of the TextBox into an array. Thus, instead of accessing the entire TextBox each time the for loop is executed, you only access the raw string data, which is all you need to do in this case.

+1


source







All Articles