From 3375e251f93c7f68d6675ecaf74bd139e1e10239 Mon Sep 17 00:00:00 2001 From: Jan Tattermusch Date: Mon, 8 Jun 2020 15:38:36 +0200 Subject: [PATCH] optimize writing non-ascii strings --- .../src/Google.Protobuf/WritingPrimitives.cs | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/csharp/src/Google.Protobuf/WritingPrimitives.cs b/csharp/src/Google.Protobuf/WritingPrimitives.cs index c317ee2bee..f85e3d8ea0 100644 --- a/csharp/src/Google.Protobuf/WritingPrimitives.cs +++ b/csharp/src/Google.Protobuf/WritingPrimitives.cs @@ -179,12 +179,23 @@ namespace Google.Protobuf } else { - // TODO: optimize this part!!!! +#if NETSTANDARD1_1 + // slowpath when Encoding.GetBytes(Char*, Int32, Byte*, Int32) is not available byte[] bytes = Utf8Encoding.GetBytes(value); WriteRawBytes(ref buffer, ref state, bytes); - // TODO: we need to write to a span... - //Utf8Encoding.GetBytes(value, 0, value.Length, buffer, state.position); - //state.position += length; +#else + ReadOnlySpan source = value.AsSpan(); + int bytesUsed; + unsafe + { + fixed (char* sourceChars = &MemoryMarshal.GetReference(source)) + fixed (byte* destinationBytes = &MemoryMarshal.GetReference(buffer.Slice(state.position))) + { + bytesUsed = Utf8Encoding.GetBytes(sourceChars, source.Length, destinationBytes, buffer.Length); + } + } + state.position += bytesUsed; +#endif } } else