Skip to content

Commit 7abb119

Browse files
committed
Use default for primitives and reference types instead of Unsafe.SkipInit.
1 parent cbd8535 commit 7abb119

File tree

3 files changed

+13
-3
lines changed

3 files changed

+13
-3
lines changed

src/BenchmarkDotNet/Code/DeclarationsProvider.cs

+2-1
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,8 @@ public override string OverheadImplementation
9090
get
9191
{
9292
var type = WorkloadMethodReturnType;
93-
if (type.IsByRefLike())
93+
bool isByRefLike = type.IsByRefLike();
94+
if (isByRefLike || (Consumer.IsConsumable(type) && !isByRefLike))
9495
{
9596
return $"return default({type.GetCorrectCSharpTypeName()});";
9697
}

src/BenchmarkDotNet/Engines/Consumer.cs

+9-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,13 @@ namespace BenchmarkDotNet.Engines
1212
{
1313
public class Consumer
1414
{
15+
private static readonly HashSet<Type> SupportedTypes
16+
= new HashSet<Type>(
17+
typeof(Consumer).GetTypeInfo()
18+
.DeclaredFields
19+
.Where(field => !field.IsStatic) // exclude this HashSet itself
20+
.Select(field => field.FieldType));
21+
1522
#pragma warning disable IDE0052 // Remove unread private members
1623
private volatile byte byteHolder;
1724
private volatile sbyte sbyteHolder;
@@ -123,7 +130,8 @@ public void Consume<T>(in T value)
123130
// This also works for empty structs, because the runtime enforces a minimum size of 1 byte.
124131
=> byteHolder = Unsafe.As<T, byte>(ref Unsafe.AsRef(in value));
125132

126-
internal static bool IsConsumable(Type type) => !type.IsByRefLike();
133+
internal static bool IsConsumable(Type type)
134+
=> SupportedTypes.Contains(type) || type.GetTypeInfo().IsClass || type.GetTypeInfo().IsInterface || !type.IsByRefLike();
127135

128136
internal static bool HasConsumableField(Type type, out FieldInfo consumableField)
129137
{

src/BenchmarkDotNet/Toolchains/InProcess/Emit/Implementation/Emitters/ConsumableConsumeEmitter.cs

+2-1
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,8 @@ protected override void OnEmitCtorBodyOverride(ConstructorBuilder constructorBui
8080

8181
public override void EmitOverheadImplementation(ILGenerator ilBuilder, Type returnType)
8282
{
83-
if (returnType.IsByRefLike())
83+
bool isByRefLike = returnType.IsByRefLike();
84+
if (isByRefLike || (Consumer.IsConsumable(returnType) && !isByRefLike))
8485
{
8586
/*
8687
// return default;

0 commit comments

Comments
 (0)