浏览代码

optimize WriteVarint64

Jan Tattermusch 5 年之前
父节点
当前提交
2f16981638
共有 1 个文件被更改,包括 22 次插入11 次删除
  1. 22 11
      csharp/src/Google.Protobuf/WritingPrimitives.cs

+ 22 - 11
csharp/src/Google.Protobuf/WritingPrimitives.cs

@@ -321,24 +321,35 @@ namespace Google.Protobuf
 
 
         public static void WriteRawVarint64(ref Span<byte> buffer, ref WriterInternalState state, ulong value)
         public static void WriteRawVarint64(ref Span<byte> buffer, ref WriterInternalState state, ulong value)
         {
         {
-            while (value > 127 && state.position < state.limit)
+            // Optimize for the common case of a single byte value
+            if (value < 128 && state.position < buffer.Length)
             {
             {
-                buffer[state.position++] = (byte)((value & 0x7F) | 0x80);
-                value >>= 7;
+                buffer[state.position++] = (byte)value;
+                return;
             }
             }
+
+            // Fast path when capacity is available
+            while (state.position < buffer.Length)
+            {
+                if (value > 127)
+                {
+                    buffer[state.position++] = (byte)((value & 0x7F) | 0x80);
+                    value >>= 7;
+                }
+                else
+                {
+                    buffer[state.position++] = (byte)value;
+                    return;
+                }
+            }
+
             while (value > 127)
             while (value > 127)
             {
             {
                 WriteRawByte(ref buffer, ref state, (byte)((value & 0x7F) | 0x80));
                 WriteRawByte(ref buffer, ref state, (byte)((value & 0x7F) | 0x80));
                 value >>= 7;
                 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 WriteRawLittleEndian32(ref Span<byte> buffer, ref WriterInternalState state, uint value)
         public static void WriteRawLittleEndian32(ref Span<byte> buffer, ref WriterInternalState state, uint value)