Skip to content

Don't store references in Consumer #2173

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 4 additions & 11 deletions src/BenchmarkDotNet/Engines/Consumer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@ private static readonly HashSet<Type> SupportedTypes
private double doubleHolder;
private long longHolder;
private ulong ulongHolder;
private string stringHolder;
private object objectHolder;
private IntPtr ptrHolder;
private UIntPtr uptrHolder;

Expand Down Expand Up @@ -97,16 +95,16 @@ private static readonly HashSet<Type> SupportedTypes

[MethodImpl(MethodImplOptions.AggressiveInlining)]
[PublicAPI]
public void Consume(string stringValue) => Volatile.Write(ref stringHolder, stringValue);
public void Consume(string stringValue) => DeadCodeEliminationHelper.KeepAliveWithoutBoxing(stringValue);

[MethodImpl(MethodImplOptions.AggressiveInlining)]
[PublicAPI]
public void Consume(object objectValue) => Volatile.Write(ref objectHolder, objectValue);
public void Consume(object objectValue) => DeadCodeEliminationHelper.KeepAliveWithoutBoxing(objectValue);

[MethodImpl(MethodImplOptions.AggressiveInlining)]
[PublicAPI]
public void Consume<T>(T objectValue) where T : class // class constraint prevents from boxing structs
=> Volatile.Write(ref objectHolder, objectValue);
=> DeadCodeEliminationHelper.KeepAliveWithoutBoxing(objectValue);

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Consume<T>(T* ptrValue) where T: unmanaged => Volatile.Write(ref ptrHolder, (IntPtr)ptrValue);
Expand Down Expand Up @@ -141,15 +139,10 @@ public void Consume<T>(in T value)
Volatile.Write(ref longHolder, (long)(object)value);
else if (typeof(T) == typeof(ulong))
Volatile.Write(ref ulongHolder, (ulong)(object)value);
else if (default(T) == null)
objectHolder = (object) value;
else
ValueTypesConsumer(value); // non-primitive value types
DeadCodeEliminationHelper.KeepAliveWithoutBoxingReadonly(value); // non-primitive and nullable value types
}

[MethodImpl(MethodImplOptions.NoInlining)]
private void ValueTypesConsumer<T>(in T _) { }

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

Expand Down