optimize ParseRawLittleEndian32

This commit is contained in:
Jan Tattermusch 2020-04-15 18:28:18 +02:00
parent 17ea4d932f
commit 373b9eaeb2

View File

@ -323,13 +323,16 @@ namespace Google.Protobuf
/// </summary> /// </summary>
public static uint ParseRawLittleEndian32(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state) public static uint ParseRawLittleEndian32(ref ReadOnlySpan<byte> buffer, ref ParserInternalState state)
{ {
const int length = sizeof(uint); const int uintLength = sizeof(uint);
if (state.bufferPos + length > state.bufferSize) const int ulongLength = sizeof(ulong);
if (state.bufferPos + ulongLength > state.bufferSize)
{ {
return ParseRawLittleEndian32SlowPath(ref buffer, ref state); return ParseRawLittleEndian32SlowPath(ref buffer, ref state);
} }
uint result = BinaryPrimitives.ReadUInt32LittleEndian(buffer.Slice(state.bufferPos, length)); // ReadUInt32LittleEndian is many times slower than ReadUInt64LittleEndian (at least on some runtimes)
state.bufferPos += length; // so it's faster better to use ReadUInt64LittleEndian and truncate the result.
uint result = (uint) BinaryPrimitives.ReadUInt64LittleEndian(buffer.Slice(state.bufferPos, ulongLength));
state.bufferPos += uintLength;
return result; return result;
} }