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

前端之家收集整理的这篇文章主要介绍了c# – 语法突出显示性能问题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个RichTextBox,一旦用户加载文件,我的程序就会继续扫描整个文件,以便更改某些单词的颜色.这是我的代码
  1. static Regex cKeyWords = new Regex(@"\b(?=[a-gilr-w])(?:
  2. s(?:hort|i(?:gned|zeof)|t(?:atic|ruct)|witch) | c(?:ase|har|on(?:st|tinue)) |
  3. e(?:lse|num|xtern) | i(?:f|nt) | f(?:loat|or) | d(?:o|efault|ouble) | un(?:ion|signed) |
  4. re(?:gister|turn) | vo(?:id|latile) | while | break | long | typedef | auto | goto
  5. )\b",RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace);
  6.  
  7. ...
  8.  
  9. programTextBox.Enabled = false;
  10. int selectStart = this.programTextBox.SelectionStart;
  11. programTextBox.SuspendLayout();
  12. MatchCollection matches = cKeyWords.Matches(programTextBox.Text);
  13. foreach (Match match in matches)
  14. {
  15. if (match.Index == 0)
  16. programTextBox.Select(match.Index,match.Length/* - 1*/);
  17. else
  18. programTextBox.Select(match.Index + 1,match.Length - 1);
  19. programTextBox.SelectionColor = Color.Blue;
  20. }
  21. programTextBox.Select(selectStart,0);
  22. programTextBox.SelectionColor = Color.Black;
  23. programTextBox.Enabled = true;
  24. programTextBox.ResumeLayout();

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

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

只需要大约0.1秒并删除

  1. programTextBox.SelectionColor = Color.Blue;

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

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

解决方法

你试过 this吗?

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

猜你在找的C#相关文章