From 551b10d7f2a42e36b518ba4c897f4f852df81de3 Mon Sep 17 00:00:00 2001 From: Traian Zaprianov Date: Tue, 22 Mar 2022 19:45:01 +0200 Subject: [PATCH] Replace several int.ToString("X", NumberFormatInfo.InvariantInfo) by using stackalloc char[] and Tryformat --- .../src/System/Xml/Core/XmlTextEncoder.cs | 26 ++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextEncoder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextEncoder.cs index 52d924a6c491df..cd5e098015cd3f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextEncoder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextEncoder.cs @@ -239,9 +239,7 @@ internal void WriteSurrogateCharEntity(char lowChar, char highChar) _attrValue.Append(lowChar); } - _textWriter.Write("&#x"); - _textWriter.Write(surrogateChar.ToString("X", NumberFormatInfo.InvariantInfo)); - _textWriter.Write(';'); + WriteIntEntityImpl(surrogateChar); } internal void Write(ReadOnlySpan text) @@ -477,16 +475,17 @@ internal void WriteCharEntity(char ch) throw new ArgumentException(SR.Xml_InvalidSurrogateMissingLowChar); } - string strVal = ((int)ch).ToString("X", NumberFormatInfo.InvariantInfo); + Span chAsSpan = stackalloc char[8]; + ((int)ch).TryFormat(chAsSpan, out int charsWritten, "X", NumberFormatInfo.InvariantInfo); if (_cacheAttrValue) { Debug.Assert(_attrValue != null); _attrValue.Append("&#x"); - _attrValue.Append(strVal); + _attrValue.Append(chAsSpan.Slice(0, charsWritten)); _attrValue.Append(';'); } - WriteCharEntityImpl(strVal); + WriteCharEntityImpl(chAsSpan.Slice(0, charsWritten)); } internal void WriteEntityRef(string name) @@ -508,13 +507,22 @@ internal void WriteEntityRef(string name) private void WriteCharEntityImpl(char ch) { - WriteCharEntityImpl(((int)ch).ToString("X", NumberFormatInfo.InvariantInfo)); + WriteIntEntityImpl(ch); + } + + private void WriteIntEntityImpl(int value) + { + Span chAsSpan = stackalloc char[8]; + if (value.TryFormat(chAsSpan, out int charsWritten, "X", NumberFormatInfo.InvariantInfo)) + WriteCharEntityImpl(chAsSpan.Slice(0, charsWritten)); + else + WriteCharEntityImpl(value.ToString("X", NumberFormatInfo.InvariantInfo)); } - private void WriteCharEntityImpl(string strVal) + private void WriteCharEntityImpl(ReadOnlySpan strSpan) { _textWriter.Write("&#x"); - _textWriter.Write(strVal); + _textWriter.Write(strSpan); _textWriter.Write(';'); }