加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 语法突出显示性能问题

发布时间:2020-12-15 07:52:28 所属栏目:百科 来源:网络整理
导读:我有一个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)) |
我有一个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();

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

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

只需要大约0.1秒并删除

programTextBox.SelectionColor = Color.Blue;

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

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

解决方法

你试过 this吗?

这阻止了绘画,实际上似乎正确地阻止它.我只有一个小的测试文件可以通过它,但它似乎工作得很好.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读