我在 XML 文件上使用 XML 文本阅读器,该文件可能包含对阅读器无效的字符。我最初的想法是创建我自己的流阅读器版本并清除坏字符,但它严重减慢了我的程序。
public class ClensingStream : StreamReader
{
private static char[] badChars = { '\x00', '\x09', '\x0A', '\x10' };
//snip
public override int Read(char[] buffer, int index, int count)
{
var tmp = base.Read(buffer, index, count);
for (int i = 0; i < buffer.Length; ++i)
{
//check the element in the buffer to see if it is one of the bad characters.
if(badChars.Contains(buffer[i]))
buffer[i] = ' ';
}
return tmp;
}
}
根据我的探查器,代码在 if(badChars.Contains(buffer[i]))
中花费了 88% 的时间慢?
最佳答案
它在该行花费这么多时间的原因是因为 Contains
方法循环遍历数组以查找字符。
将字符放在HashSet<char>
中相反:
private static HashSet<char> badChars =
new HashSet<char>(new char[] { '\x00', '\x09', '\x0A', '\x10' });
检查集合是否包含字符的代码看起来与在数组中查找相同,但它使用字符的哈希码来查找它而不是遍历数组中的所有项目。
或者,您可以将字符放在一个开关中,这样编译器将创建一个有效的比较:
switch (buffer[i]]) {
case '\x00':
case '\x09':
case '\x0A':
case '\x10': buffer[i] = ' '; break;
}
如果你有更多的字符(5 或 6 个 IIRC),编译器实际上会创建一个哈希表来查找案例,所以这类似于使用 HashSet
.
关于c# - 如何快速替换数组中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5261858/