Description
While debugging and attempting to fix flaky allocation measurements in BenchmarkDotNet (dotnet/BenchmarkDotNet#2562), I found that System.Runtime.InteropServices.RuntimeInformation causes allocations during a GC.Collect().
I only observe this behavior in net8.0 runtime. net48 runtime using Microsoft.DotNet.PlatformAbstractions nuget package does not reproduce (or AppDomain.MonitoringTotalAllocatedMemorySize just doesn't observe it, since GC.GetTotalAllocatedBytes is not available in net48).
Reproduction Steps
Create a Console application and run this code in Release with net8.0.
public static void Main()
{
var bench = new Bench();
var action = bench.Benchmark1;
Warmup(action);
// Switch these lines to observe 0 allocated bytes.
var frameworkDescription = RuntimeInformation.FrameworkDescription;
//var frameworkDescription = "";
var initial = GetAllocatedBytes();
action();
var final = GetAllocatedBytes();
Console.WriteLine($"allocated bytes: {final - initial}");
GC.KeepAlive(frameworkDescription);
}
static long GetAllocatedBytes()
{
GC.Collect(); // We only observe allocated bytes when GC.Collect() is called.
return GC.GetTotalAllocatedBytes(precise: true);
}
static void Warmup(Action action)
{
for (int i = 0; i < 100; i++)
{
action();
}
}
public class Bench
{
public void Benchmark1() => TestMethod();
[MethodImpl(MethodImplOptions.NoInlining)]
public static ulong TestMethod()
{
var r = 1ul;
for (var i = 0; i < 50_000_000; i++)
{
r /= 1;
}
return r;
}
}
Expected behavior
Console prints allocated bytes: 0.
Actual behavior
Console prints allocated bytes: 336 (sometimes it prints 48 or 672).
Regression?
No response
Known Workarounds
No response
Configuration
Windows 10 x64
.Net 8.0
Other information
No response
Description
While debugging and attempting to fix flaky allocation measurements in BenchmarkDotNet (dotnet/BenchmarkDotNet#2562), I found that
System.Runtime.InteropServices.RuntimeInformationcauses allocations during aGC.Collect().I only observe this behavior in
net8.0runtime.net48runtime usingMicrosoft.DotNet.PlatformAbstractionsnuget package does not reproduce (orAppDomain.MonitoringTotalAllocatedMemorySizejust doesn't observe it, sinceGC.GetTotalAllocatedBytesis not available innet48).Reproduction Steps
Create a Console application and run this code in Release with net8.0.
Expected behavior
Console prints
allocated bytes: 0.Actual behavior
Console prints
allocated bytes: 336(sometimes it prints 48 or 672).Regression?
No response
Known Workarounds
No response
Configuration
Windows 10 x64
.Net 8.0
Other information
No response