From b3c550baae2c21ff02b06e0cbd982df3b87b89f7 Mon Sep 17 00:00:00 2001 From: Brant Burnett Date: Fri, 12 Jul 2024 14:26:31 -0400 Subject: [PATCH] Optimize Read to use Math.Min Math.Min can be optimized to a single instruction on some CPU architectures and avoid a branch. This also makes the method smaller. --- Snappier/Internal/SnappyDecompressor.cs | 19 +++++-------------- 1 file changed, 5 insertions(+), 14 deletions(-) diff --git a/Snappier/Internal/SnappyDecompressor.cs b/Snappier/Internal/SnappyDecompressor.cs index a263837..871ee3f 100644 --- a/Snappier/Internal/SnappyDecompressor.cs +++ b/Snappier/Internal/SnappyDecompressor.cs @@ -613,24 +613,15 @@ private static void AppendFromSelf(ref byte op, ref byte buffer, ref byte buffer public int Read(Span destination) { - int unreadBytes = UnreadBytes; - if (unreadBytes == 0) + var bytesToRead = Math.Min(destination.Length, UnreadBytes); + if (bytesToRead <= 0) { return 0; } - if (unreadBytes >= destination.Length) - { - _lookbackBuffer.Span.Slice(_readPosition, destination.Length).CopyTo(destination); - _readPosition += destination.Length; - return destination.Length; - } - else - { - _lookbackBuffer.Span.Slice(_readPosition, unreadBytes).CopyTo(destination); - _readPosition += unreadBytes; - return unreadBytes; - } + _lookbackBuffer.Span.Slice(_readPosition, bytesToRead).CopyTo(destination); + _readPosition += bytesToRead; + return bytesToRead; } ///