Skip to content

Instantly share code, notes, and snippets.

@teoadal
Last active March 15, 2023 07:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teoadal/b93f7fd98f00f8f988a09ead990e2fbf to your computer and use it in GitHub Desktop.
Save teoadal/b93f7fd98f00f8f988a09ead990e2fbf to your computer and use it in GitHub Desktop.
using System.Runtime.CompilerServices;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
namespace Storage.Benchmark;
[SimpleJob(RuntimeMoniker.Net60)]
[SimpleJob(RuntimeMoniker.NetCoreApp31)]
[SimpleJob(RuntimeMoniker.Net48)]
[MeanColumn]
public class InliningBenchmark
{
[Benchmark]
public int AggressiveInline()
{
var service = _service;
var sum = 0;
foreach (var i in _numbers)
{
sum += service.AggressiveInline(i, i);
}
return sum;
}
[Benchmark(Baseline = true)]
public int AutoInline()
{
var service = _service;
var sum = 0;
foreach (var i in _numbers)
{
sum += service.AutoInline(i, i);
}
return sum;
}
[Benchmark]
public int WithoutInline()
{
var service = _service;
var sum = 0;
foreach (var i in _numbers)
{
sum += service.WithoutInline(i, i);
}
return sum;
}
#region Configuration
private int[] _numbers = null!;
private InliningService _service = null!;
[GlobalSetup]
public void Init()
{
var random = new Random(1234);
_numbers = Enumerable.Range(0, 100).Select(_ => random.Next(0, 1000)).ToArray();
_service = new InliningService(0);
}
#endregion
}
public sealed class InliningService
{
private readonly int _min;
public InliningService(int min)
{
_min = min;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int AggressiveInline(int a, int b)
{
if (a < _min || b < _min) throw new InvalidOperationException("A and B must be positive");
return a + b;
}
public int AutoInline(int a, int b)
{
if (a < _min || b < _min) Errors.InvalidOperation("A and B must be positive");
return a + b;
}
public int WithoutInline(int a, int b)
{
if (a < _min || b < _min) throw new InvalidOperationException("A and B must be positive");
return a + b;
}
}
internal static class Errors
{
public static void InvalidOperation(string message)
{
throw new Exception(message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment