views:

162

answers:

2

Hi,

I have a RichTextBox, and there are about more than 1000 occurrences of a specified search string.

I use the following function to color all the occurrences:

public void ColorAll(string s)
{
    rtbxContent.BeginUpdate();

    int start = 0, current = 0;
    RichTextBoxFinds options = RichTextBoxFinds.MatchCase;
    start = rtbxContent.Find(s, start, options);
    while (start >= 0)
    {
        rtbxContent.SelectionStart  = start;
        rtbxContent.SelectionLength = s.Length;
        rtbxContent.SelectionColor     = Color.Red;
        rtbxContent.SelectionBackColor = Color.Yellow;

        current = start + s.Length;
        if (current < rtbxContent.TextLength)
            start = rtbxContent.Find(s, current, options);
        else
            break;
    }

    rtbxContent.EndUpdate();
}

But I found it's very slow.

However, if I color all the occurrences of another word, which has less number of occurrences in the same text, I found it's very fast.

So I guess the slowness is from (these two line might get UI refresh involved):

    rtbxContent.SelectionColor     = Color.Red;
    rtbxContent.SelectionBackColor = Color.Yellow;

Is there a faster way of doing the same job, such as, I do the coloring in the memory, and then I display the result at one-go?

Do I make myself clear?

Thanks.

A: 

The amount of time it takes is directly proportional to the number of occurances.

It is probably the Find that is using the most time. You could replace this line:

    start = rtbxContent.Find(s, start + s.Length, options); 

with this:

    start = rtbxContent.Find(s, current, options);

Since you have computed current to equal start + s.Length

You could also store s.Length is a variable so you do not need to count all the characters in a string each time. The same goes for rtbxContent.TextLength.

Shiraz Bhaiji
Thanks for your reminding. I did forget to replace "start+s.Length" with current :-)
Peter Lee
A: 

The string search is linear. If you find Find method to be slow, maybe you can use third party tool to do the searching for you. All you need is index of the pattern in a string.

Maybe this will help you. You should time the difference and use the faster one.

Nayan
Thanks for your reply. I'm not sure whether my guess is right or not. I don't think the "Find" method is the main reason causing it so slow. I think it might be the UI update/refresh make it slow.
Peter Lee
Then why don't you time the individual code pieces? You'll know where the problem might be.
Nayan