From 8e91ff8699ef09913b24e3be9ad2649972e1d367 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Wed, 6 Mar 2019 11:10:46 -0800 Subject: [PATCH] Reduce overhead of ReadOnlySequence.CopyTo (dotnet/corefx#35819) `ReadOnlySequence.Length` isn't as small or fast as `ReadOnlySpan.Length`, which is just a field access. Since we need the span anyway for the single element case, just get the span first and then compare with its length. Commit migrated from https://github.com/dotnet/corefx/commit/7fc9d5730aabc6724edf18f5bedde6d32610f681 --- .../System.Memory/src/System/Buffers/BuffersExtensions.cs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/libraries/System.Memory/src/System/Buffers/BuffersExtensions.cs b/src/libraries/System.Memory/src/System/Buffers/BuffersExtensions.cs index fc3f0ea..b8c5f8d 100644 --- a/src/libraries/System.Memory/src/System/Buffers/BuffersExtensions.cs +++ b/src/libraries/System.Memory/src/System/Buffers/BuffersExtensions.cs @@ -63,12 +63,12 @@ namespace System.Buffers [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void CopyTo(in this ReadOnlySequence source, Span destination) { - if (source.Length > destination.Length) - ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.destination); - if (source.IsSingleSegment) { - source.First.Span.CopyTo(destination); + ReadOnlySpan span = source.First.Span; + if (span.Length > destination.Length) + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.destination); + span.CopyTo(destination); } else { @@ -78,6 +78,9 @@ namespace System.Buffers private static void CopyToMultiSegment(in ReadOnlySequence sequence, Span destination) { + if (sequence.Length > destination.Length) + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.destination); + SequencePosition position = sequence.Start; while (sequence.TryGet(ref position, out ReadOnlyMemory memory)) { -- 2.7.4