From 21f9dd5032fe51e10b3442a150ed01f3bf2e53bc Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Thu, 17 Dec 2020 08:34:07 +1300 Subject: [PATCH] Optimize remainder --- .../src/Google.Protobuf/WritingPrimitives.cs | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/csharp/src/Google.Protobuf/WritingPrimitives.cs b/csharp/src/Google.Protobuf/WritingPrimitives.cs index d8e1fbe7dd80..bcb0c01ab274 100644 --- a/csharp/src/Google.Protobuf/WritingPrimitives.cs +++ b/csharp/src/Google.Protobuf/WritingPrimitives.cs @@ -179,8 +179,6 @@ public static void WriteString(ref Span buffer, ref WriterInternalState st { if (length == value.Length) // Must be all ASCII... { - int currentIndex = 0; - // If 64bit, and value has at least 4 chars, process 4 chars at a time. if (IntPtr.Size == 8 && value.Length >= 4) { @@ -190,6 +188,7 @@ public static void WriteString(ref Span buffer, ref WriterInternalState st // Process 4 chars at a time until there are less than 4 remaining. // We already know all characters are ASCII so there is no need to validate the source. int lastIndexWhereCanReadFourChars = value.Length - 4; + int currentIndex = 0; do { NarrowFourUtf16CharsToAsciiAndWriteToBuffer( @@ -198,14 +197,19 @@ public static void WriteString(ref Span buffer, ref WriterInternalState st } while ((currentIndex += 4) <= lastIndexWhereCanReadFourChars); - // Any chars remaining are processed in for loop below. + // Process remainder. + for (; currentIndex < length; currentIndex++) + { + Unsafe.AddByteOffset(ref destinationBytes, (IntPtr)currentIndex) = Unsafe.AddByteOffset(ref sourceBytes, (IntPtr)(currentIndex * 2)); + } } - - for (int i = currentIndex; i < length; i++) + else { - buffer[state.position + i] = (byte)value[i]; + for (int i = 0; i < length; i++) + { + buffer[state.position + i] = (byte)value[i]; + } } - state.position += length; } else