From aabae6de150ff955f1fa57a90906cad5e62a14c4 Mon Sep 17 00:00:00 2001 From: Bradley Grainger Date: Sun, 13 Aug 2023 07:45:22 -0700 Subject: [PATCH] Use one-shot UTF-8 encoding when possible. This avoids allocating a EncoderNLS object and making multiple passes over the source data when the entire string could be converted at once. Additionally, UTF8Encoding.GetBytes is more likely to be highly optimized in the framework. --- .../Protocol/Serialization/ByteBufferWriter.cs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/MySqlConnector/Protocol/Serialization/ByteBufferWriter.cs b/src/MySqlConnector/Protocol/Serialization/ByteBufferWriter.cs index 5819aa2ab..aabcae82a 100644 --- a/src/MySqlConnector/Protocol/Serialization/ByteBufferWriter.cs +++ b/src/MySqlConnector/Protocol/Serialization/ByteBufferWriter.cs @@ -99,11 +99,22 @@ public void Write(ReadOnlySpan span) m_output = m_output[span.Length..]; } - public void Write(string value) => Write(value.AsSpan(), flush: true); + public void Write(string value) => Write(value.AsSpan()); public void WriteAscii(string value) => WriteAscii(value.AsSpan()); - public void Write(string value, int offset, int length) => Write(value.AsSpan(offset, length), flush: true); + public void Write(string value, int offset, int length) => Write(value.AsSpan(offset, length)); + + public void Write(ReadOnlySpan chars) + { + if (m_output.Length < chars.Length * 3) + { + var neededBytes = Encoding.UTF8.GetByteCount(chars); + if (m_output.Length < neededBytes) + Reallocate(neededBytes); + } + m_output = m_output[Encoding.UTF8.GetBytes(chars, m_output.Span)..]; + } public void Write(ReadOnlySpan chars, bool flush) { @@ -273,7 +284,7 @@ public static void WriteLengthEncodedString(this ByteBufferWriter writer, ReadOn { var byteCount = Encoding.UTF8.GetByteCount(value); writer.WriteLengthEncodedInteger((ulong) byteCount); - writer.Write(value, flush: true); + writer.Write(value); } public static void WriteLengthEncodedAsciiString(this ByteBufferWriter writer, string value)