我有一个网站上不允许出现的 200 多个单词的列表。下面的string.Replace
方法大约需要 80 毫秒。如果我将这个延迟增加s < 1000
10.00 倍s < 10,000
到 ~834 毫秒,增加了 10.43。我担心这个功能的可扩展性,尤其是当列表增加时。有人告诉我字符串是不可变的,并且text.Replace()
正在内存中创建 200 个新字符串。有没有类似于 aStringbuilder
的东西?
List<string> FilteredWords = new List<string>();
FilteredWords.Add("RED");
FilteredWords.Add("GREEN");
FilteredWords.Add("BLACK");
for (int i = 1; i < 200; i++)
{ FilteredWords.Add("STRING " + i.ToString()); }
string text = "";
//simulate a large dynamically generated html page
for (int s = 1; s < 1000; s++)
{ text += @"Lorem ipsum dolor sit amet, minim BLACK cetero cu nam.
No vix platonem sententiae, pro wisi congue graecis id, GREEN assum interesset in vix.
Eum tamquam RED pertinacia ex."; }
// This is the function I seek to optimize
foreach (string s in FilteredWords)
{ text = text.Replace(s, "[REMOVED]"); }