Skip to content

Instantly share code, notes, and snippets.

@MaciekSwiszczowski
Created December 9, 2018 18:56
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 MaciekSwiszczowski/fd561f74db8e907eea0dbd3ec606253a to your computer and use it in GitHub Desktop.
Save MaciekSwiszczowski/fd561f74db8e907eea0dbd3ec606253a to your computer and use it in GitHub Desktop.
using System;
using BenchmarkDotNet.Attributes;
using static BenchmarkDotNet.Diagnosers.HardwareCounter;
namespace Benchmarks.Branching
{
internal class ReferenceType
{
public int Value;
}
internal struct ValueType
{
public int Value;
}
internal struct ExtendedValueType
{
public int Value;
private double _otherData;
}
[HardwareCounters(CacheMisses, BranchInstructions, BranchMispredictions)]
public class ClassVsStruct
{
private ReferenceType[] _referenceTypeData;
private ValueType[] _valueTypeData;
private ExtendedValueType[] _extendedValueTypeData;
private int[] _data;
[Params(100, 500, 1000/*, 10000, 100_000*/)]
public int Size { get; set; }
[GlobalSetup]
public void GlobalSetup()
{
_referenceTypeData = new ReferenceType[Size];
_valueTypeData = new ValueType[Size];
_extendedValueTypeData = new ExtendedValueType[Size];
_data = new int[Size];
var random = new Random();
for (var i = 0; i < Size; i++)
{
_data[i] = random.Next(100000);
_referenceTypeData[i] = new ReferenceType { Value = _data[i] };
_valueTypeData[i] = new ValueType { Value = _data[i] };
_extendedValueTypeData[i] = new ExtendedValueType { Value = _data[i] };
}
}
[Benchmark(Baseline = true)]
public int ReferenceTypeSum()
{
var sum = 0;
for (var i = 0; i < Size; i++)
{
sum += _referenceTypeData[i].Value;
}
return sum;
}
[Benchmark]
public int ValueTypeSum()
{
var sum = 0;
for (var i = 0; i < Size; i++)
{
sum += _valueTypeData[i].Value;
}
return sum;
}
[Benchmark]
public int ExtendedValueTypeSum()
{
var sum = 0;
for (var i = 0; i < Size; i++)
{
sum += _extendedValueTypeData[i].Value;
}
return sum;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment