3 回答
TA贡献1807条经验 获得超9个赞
这是上述方法RemoveInvalidXmlChars的优化版本,该方法不会在每次调用时都创建一个新数组,因此不必要地给GC施加了压力:
public static string RemoveInvalidXmlChars(string text)
{
if (text == null)
return text;
if (text.Length == 0)
return text;
// a bit complicated, but avoids memory usage if not necessary
StringBuilder result = null;
for (int i = 0; i < text.Length; i++)
{
var ch = text[i];
if (XmlConvert.IsXmlChar(ch))
{
result?.Append(ch);
}
else if (result == null)
{
result = new StringBuilder();
result.Append(text.Substring(0, i));
}
}
if (result == null)
return text; // no invalid xml chars detected - return original text
else
return result.ToString();
}
- 3 回答
- 0 关注
- 1036 浏览
添加回答
举报