Skip to content

Commit b93f42f

Browse files
committed
Minor optimization to Stream.Read<T>
1 parent 38fe889 commit b93f42f

File tree

1 file changed

+9
-9
lines changed

1 file changed

+9
-9
lines changed

Microsoft.Toolkit.HighPerformance/Extensions/StreamExtensions.cs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -167,24 +167,24 @@ public static void Write(this Stream stream, ReadOnlySpan<byte> buffer)
167167
/// <returns>The <typeparamref name="T"/> value read from <paramref name="stream"/>.</returns>
168168
/// <exception cref="InvalidOperationException">Thrown if <paramref name="stream"/> reaches the end.</exception>
169169
#if SPAN_RUNTIME_SUPPORT
170-
// Avoid inlining as we're renting a stack buffer, which
171-
// cause issues if this method was called inside a loop
172-
[MethodImpl(MethodImplOptions.NoInlining)]
170+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
173171
#endif
174172
public static T Read<T>(this Stream stream)
175173
where T : unmanaged
176174
{
177175
#if SPAN_RUNTIME_SUPPORT
178-
Span<byte> span = stackalloc byte[Unsafe.SizeOf<T>()];
176+
T result = default;
177+
int length = Unsafe.SizeOf<T>();
179178

180-
if (stream.Read(span) != span.Length)
179+
unsafe
181180
{
182-
ThrowInvalidOperationExceptionForEndOfStream();
181+
if (stream.Read(new Span<byte>(&result, length)) != length)
182+
{
183+
ThrowInvalidOperationExceptionForEndOfStream();
184+
}
183185
}
184186

185-
ref byte r0 = ref MemoryMarshal.GetReference(span);
186-
187-
return Unsafe.ReadUnaligned<T>(ref r0);
187+
return result;
188188
#else
189189
int length = Unsafe.SizeOf<T>();
190190
byte[] buffer = ArrayPool<byte>.Shared.Rent(length);

0 commit comments

Comments
 (0)