语法突出显示性能问题

OC_*_*OC_ 7 c# regex syntax-highlighting richtextbox winforms

我有一个RichTextBox,一旦用户加载文件,我的程序就会继续扫描整个文件,以便更改某些单词的颜色.这是我的代码:

static Regex cKeyWords = new Regex(@"\b(?=[a-gilr-w])(?:
     s(?:hort|i(?:gned|zeof)|t(?:atic|ruct)|witch) | c(?:ase|har|on(?:st|tinue)) |
     e(?:lse|num|xtern) | i(?:f|nt) | f(?:loat|or) | d(?:o|efault|ouble) | un(?:ion|signed) |
     re(?:gister|turn) | vo(?:id|latile) | while | break | long | typedef | auto | goto
     )\b",
     RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace);

...

programTextBox.Enabled = false;
int selectStart = this.programTextBox.SelectionStart;
programTextBox.SuspendLayout();
MatchCollection matches = cKeyWords.Matches(programTextBox.Text);
foreach (Match match in matches)
{
    if (match.Index == 0)
        programTextBox.Select(match.Index, match.Length/* - 1*/);
    else
        programTextBox.Select(match.Index + 1, match.Length - 1);
    programTextBox.SelectionColor = Color.Blue;
}
programTextBox.Select(selectStart, 0);
programTextBox.SelectionColor = Color.Black;
programTextBox.Enabled = true;
programTextBox.ResumeLayout();
Run Code Online (Sandbox Code Playgroud)

问题:我的代码需要大约5秒半的时间来扫描和更改具有200,000个字符的文件中所有关键字的颜色.

我之前被告知我不应该使用正则表达式来做这种事情,但经过几次测试我发现: MatchCollection matches = cKeyWords.Matches(programTextBox.Text);

只需要大约0.1秒并删除

programTextBox.SelectionColor = Color.Blue;
Run Code Online (Sandbox Code Playgroud)

将代码的总执行时间从5.5秒减少到大约0.3秒

怎么样?为什么?最重要的是:我该怎么办?

Bug*_*der 0

你试过这个吗?

这会阻止绘画,而且实际上似乎正确地阻止了它。我只有一个小测试文件来完成它,但它似乎工作得很好。