Skip to content

Commit

Permalink
Use default for primitives and reference types instead of Unsafe.Skip…
Browse files Browse the repository at this point in the history
…Init.
  • Loading branch information
timcassell committed May 17, 2023
1 parent cbd8535 commit 7abb119
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 3 deletions.
3 changes: 2 additions & 1 deletion src/BenchmarkDotNet/Code/DeclarationsProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,8 @@ public override string OverheadImplementation
get
{
var type = WorkloadMethodReturnType;
if (type.IsByRefLike())
bool isByRefLike = type.IsByRefLike();
if (isByRefLike || (Consumer.IsConsumable(type) && !isByRefLike))
{
return $"return default({type.GetCorrectCSharpTypeName()});";
}
Expand Down
10 changes: 9 additions & 1 deletion src/BenchmarkDotNet/Engines/Consumer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ namespace BenchmarkDotNet.Engines
{
public class Consumer
{
private static readonly HashSet<Type> SupportedTypes
= new HashSet<Type>(
typeof(Consumer).GetTypeInfo()
.DeclaredFields
.Where(field => !field.IsStatic) // exclude this HashSet itself
.Select(field => field.FieldType));

#pragma warning disable IDE0052 // Remove unread private members
private volatile byte byteHolder;
private volatile sbyte sbyteHolder;
Expand Down Expand Up @@ -123,7 +130,8 @@ public void Consume<T>(in T value)
// This also works for empty structs, because the runtime enforces a minimum size of 1 byte.
=> byteHolder = Unsafe.As<T, byte>(ref Unsafe.AsRef(in value));

internal static bool IsConsumable(Type type) => !type.IsByRefLike();
internal static bool IsConsumable(Type type)
=> SupportedTypes.Contains(type) || type.GetTypeInfo().IsClass || type.GetTypeInfo().IsInterface || !type.IsByRefLike();

internal static bool HasConsumableField(Type type, out FieldInfo consumableField)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,8 @@ protected override void OnEmitCtorBodyOverride(ConstructorBuilder constructorBui

public override void EmitOverheadImplementation(ILGenerator ilBuilder, Type returnType)
{
if (returnType.IsByRefLike())
bool isByRefLike = returnType.IsByRefLike();
if (isByRefLike || (Consumer.IsConsumable(returnType) && !isByRefLike))
{
/*
// return default;
Expand Down

0 comments on commit 7abb119

Please sign in to comment.