3 回答

TA貢獻1807條經(jīng)驗 獲得超9個贊
這是上述方法RemoveInvalidXmlChars的優(yōu)化版本,該方法不會在每次調(diào)用時都創(chuàng)建一個新數(shù)組,因此不必要地給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 關(guān)注
- 1067 瀏覽
添加回答
舉報