From 2693073babef1ae5f40686864bc1a64747fd0319 Mon Sep 17 00:00:00 2001 From: Jan Kotas Date: Fri, 20 Oct 2023 23:58:28 -0700 Subject: [PATCH] Add microbenchmark for core UnmanagedMemoryStream scenario Related to https://github.com/dotnet/runtime/pull/93766 --- .../System.IO/UnmanagedMemoryStreamTests.cs | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/benchmarks/micro/libraries/System.IO/UnmanagedMemoryStreamTests.cs diff --git a/src/benchmarks/micro/libraries/System.IO/UnmanagedMemoryStreamTests.cs b/src/benchmarks/micro/libraries/System.IO/UnmanagedMemoryStreamTests.cs new file mode 100644 index 0000000000..7c87bec5c9 --- /dev/null +++ b/src/benchmarks/micro/libraries/System.IO/UnmanagedMemoryStreamTests.cs @@ -0,0 +1,53 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.IO; +using System.Runtime.InteropServices; +using BenchmarkDotNet.Attributes; +using MicroBenchmarks; + +namespace System.IO.Tests +{ + [BenchmarkCategory(Categories.Libraries)] + public unsafe class UnmanagedMemoryStreamTests + { + private const int Length = 10000; + private byte* buffer; + + [GlobalSetup] + public void Setup() + { + buffer = (byte*)Marshal.AllocCoTaskMem(Length); + } + + [GlobalCleanup] + public void Cleanup() + { + Marshal.FreeCoTaskMem((IntPtr)buffer); + } + + [Benchmark] + public void ReadAsBytes() + { + using (var ums = new UnmanagedMemoryStream(buffer, Length)) + { + while (ums.ReadByte() >= 0) + { + } + } + } + + [Benchmark] + public void ReadAsArrays() + { + var array = new byte[1]; + using (var ums = new UnmanagedMemoryStream(buffer, Length)) + { + while (ums.Read(array, 0, array.Length) != 0) + { + } + } + } + } +}