From 9d53fadcac83f79b24f47b49a5a1489f917d556d Mon Sep 17 00:00:00 2001 From: Jan Tattermusch Date: Tue, 23 Jun 2020 17:23:21 +0200 Subject: [PATCH] optimize WriteVarint32 --- .../src/Google.Protobuf/WritingPrimitives.cs | 28 +++++++++++-------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/csharp/src/Google.Protobuf/WritingPrimitives.cs b/csharp/src/Google.Protobuf/WritingPrimitives.cs index afa6e986e6..863bde0c20 100644 --- a/csharp/src/Google.Protobuf/WritingPrimitives.cs +++ b/csharp/src/Google.Protobuf/WritingPrimitives.cs @@ -289,30 +289,34 @@ namespace Google.Protobuf public static void WriteRawVarint32(ref Span buffer, ref WriterInternalState state, uint value) { // Optimize for the common case of a single byte value - if (value < 128 && state.position < state.limit) + if (value < 128 && state.position < buffer.Length) { buffer[state.position++] = (byte)value; return; } - while (value > 127 && state.position < state.limit) + // Fast path when capacity is available + while (state.position < buffer.Length) { - buffer[state.position++] = (byte)((value & 0x7F) | 0x80); - value >>= 7; + if (value > 127) + { + buffer[state.position++] = (byte)((value & 0x7F) | 0x80); + value >>= 7; + } + else + { + buffer[state.position++] = (byte)value; + return; + } } + while (value > 127) { WriteRawByte(ref buffer, ref state, (byte)((value & 0x7F) | 0x80)); value >>= 7; } - if (state.position < state.limit) - { - buffer[state.position++] = (byte)value; - } - else - { - WriteRawByte(ref buffer, ref state, (byte)value); - } + + WriteRawByte(ref buffer, ref state, (byte)value); } public static void WriteRawVarint64(ref Span buffer, ref WriterInternalState state, ulong value)