Optimize Span.GetPinnableReference (dotnet/coreclr#20428)
authorJan Kotas <jkotas@microsoft.com>
Tue, 16 Oct 2018 04:39:18 +0000 (21:39 -0700)
committerGitHub <noreply@github.com>
Tue, 16 Oct 2018 04:39:18 +0000 (21:39 -0700)
* Optimize Span.GetPinnableReference

* CR feedback

Commit migrated from https://github.com/dotnet/coreclr/commit/d3ed7cb8da830657c376d4adb2862bc3c09cfef7

src/libraries/System.Private.CoreLib/src/System/ReadOnlySpan.Fast.cs
src/libraries/System.Private.CoreLib/src/System/Span.Fast.cs

index 4fb039a..8ba8fd6 100644 (file)
@@ -153,7 +153,13 @@ namespace System
         /// It can be used for pinning and is required to support the use of span within a fixed statement.
         /// </summary>
         [EditorBrowsable(EditorBrowsableState.Never)]
-        public unsafe ref readonly T GetPinnableReference() => ref (_length != 0) ? ref _pointer.Value : ref Unsafe.AsRef<T>(null);
+        public unsafe ref readonly T GetPinnableReference()
+        {
+            // Ensure that the native code has just one forward branch that is predicted-not-taken.
+            ref T ret = ref Unsafe.AsRef<T>(null);
+            if (_length != 0) ret = ref _pointer.Value;
+            return ref ret;
+        }
 
         /// <summary>
         /// Copies the contents of this read-only span into destination span. If the source
index b3cfc8d..3073592 100644 (file)
@@ -158,7 +158,13 @@ namespace System
         /// It can be used for pinning and is required to support the use of span within a fixed statement.
         /// </summary>
         [EditorBrowsable(EditorBrowsableState.Never)]
-        public unsafe ref T GetPinnableReference() => ref (_length != 0) ? ref _pointer.Value : ref Unsafe.AsRef<T>(null);
+        public unsafe ref T GetPinnableReference()
+        {
+            // Ensure that the native code has just one forward branch that is predicted-not-taken.
+            ref T ret = ref Unsafe.AsRef<T>(null);
+            if (_length != 0) ret = ref _pointer.Value;
+            return ref ret;
+        }
 
         /// <summary>
         /// Clears the contents of this span.