Skip to content

Instantly share code, notes, and snippets.

@controlflow
Created Jul 14, 2021
Embed
What would you like to do?
Null check benchmarks
using System;
using System.Runtime.CompilerServices;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;
// ReSharper disable RedundantToStringCall
// ReSharper disable NotAccessedField.Local
#pragma warning disable 169
BenchmarkRunner.Run<NullChecksBenchmark>();
[SimpleJob(RuntimeMoniker.Net48)]
[SimpleJob(RuntimeMoniker.NetCoreApp31)]
[SimpleJob(RuntimeMoniker.Net50)]
[SimpleJob(RuntimeMoniker.Net60)]
public class NullChecksBenchmark
{
private readonly string[] myBox = { "abc" };
private string myField;
private int myField2;
private const int Count = 100;
[Benchmark]
public void IfThenThrow() => IfThenThrow(myBox[0]);
private void IfThenThrow(string s)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
// do some work
// for (var index = 0; index < Count; index++)
// {
// myField = s.ToString();
// myField2 = index;
// }
myField = s.ToString();
}
[Benchmark]
public void HelperMethod() => HelperMethod(myBox[0]);
private void HelperMethod(string s)
{
if (s == null)
ThrowHelper(nameof(s));
// do some work
// for (var index = 0; index < Count; index++)
// {
// myField = s.ToString();
// myField2 = index;
// }
myField = s.ToString();
}
private static void ThrowHelper( string parameterName)
{
throw new ArgumentNullException(parameterName);
}
[Benchmark]
public void HelperMethodNoInline() => HelperMethodNoInline(myBox[0]);
private void HelperMethodNoInline(string s)
{
if (s == null)
ThrowHelperNoInline(nameof(s));
// do some work
// for (var index = 0; index < Count; index++)
// {
// myField = s.ToString();
// myField2 = index;
// }
myField = s.ToString();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowHelperNoInline(string parameterName)
{
throw new ArgumentNullException(parameterName);
}
[Benchmark]
public void HelperMethodNoArgs() => HelperMethodNoArgs(myBox[0]);
private void HelperMethodNoArgs(string s)
{
if (s == null)
ThrowHelperNoArgs();
// do some work
// for (var index = 0; index < Count; index++)
// {
// myField = s.ToString();
// myField2 = index;
// }
myField = s.ToString();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowHelperNoArgs()
{
throw new ArgumentNullException("s");
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>net48;netcoreapp3.1;net5.0;net6.0</TargetFrameworks>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.13.0" />
</ItemGroup>
</Project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment