Skip to content

Commit

Permalink
Use one-shot UTF-8 encoding when possible.
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
bgrainger committed Aug 13, 2023
1 parent 845461c commit aabae6d
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/MySqlConnector/Protocol/Serialization/ByteBufferWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,22 @@ public void Write(ReadOnlySpan<byte> 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<char> 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<char> chars, bool flush)
{
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit aabae6d

Please sign in to comment.