Skip to content

Commit 1100f76

Browse files
committed
Add microbenchmark for core UnmanagedMemoryStream scenario
Related to dotnet/runtime#93766
1 parent ce59089 commit 1100f76

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for more information.
4+
5+
using System.IO;
6+
using System.Runtime.InteropServices;
7+
using BenchmarkDotNet.Attributes;
8+
using MicroBenchmarks;
9+
10+
namespace System.IO.Tests
11+
{
12+
[BenchmarkCategory(Categories.Libraries)]
13+
public unsafe class UnmanagedMemoryStreamTests
14+
{
15+
private const int Length = 10000;
16+
private byte* buffer;
17+
18+
[GlobalSetup]
19+
public void Setup()
20+
{
21+
buffer = (byte*)NativeMemory.Alloc(Length);
22+
}
23+
24+
[GlobalCleanup]
25+
public void Cleanup()
26+
{
27+
NativeMemory.Free(buffer);
28+
}
29+
30+
[Benchmark]
31+
public void ReadAsBytes()
32+
{
33+
using (UnmanagedMemoryStream ums = new(buffer, Length))
34+
{
35+
while (ums.ReadByte() >= 0)
36+
{
37+
}
38+
}
39+
}
40+
41+
[Benchmark]
42+
public void ReadAsSpans()
43+
{
44+
Span<byte> span = stackalloc byte[1];
45+
using (UnmanagedMemoryStream ums = new(buffer, Length))
46+
{
47+
while (ums.Read(span) != 0)
48+
{
49+
}
50+
}
51+
}
52+
}
53+
}

0 commit comments

Comments
 (0)