optimize WriteVarint64

pull/7576/head
Jan Tattermusch 4 years ago
parent 9d53fadcac
commit 2f16981638
  1. 33
      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); buffer[state.position++] = (byte)value;
value >>= 7; 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)
{ WriteRawByte(ref buffer, ref state, (byte)value);
buffer[state.position++] = (byte)value;
}
else
{
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)

Loading…
Cancel
Save