Skip to content

Instantly share code, notes, and snippets.

@phil-scott-78
Last active April 2, 2017 23:17
Show Gist options
  • Save phil-scott-78/863f3d3f2b30addb66ded9b16665cd81 to your computer and use it in GitHub Desktop.
Save phil-scott-78/863f3d3f2b30addb66ded9b16665cd81 to your computer and use it in GitHub Desktop.
field or property
using System;
using System.Collections.Generic;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Running;
namespace Benchmark
{
class Program
{
static void Main()
{
var summary = BenchmarkRunner.Run<WeigherBenchmark>(DefaultConfig.Instance.With(new MemoryDiagnoser()));
}
}
public class WeigherBenchmark
{
List<ObjToWeigh> _objs = new List<ObjToWeigh>();
[Setup]
public void Setup()
{
int objsCount = 500000;
Random rng = new Random();
for (int z = 0; z < objsCount; z++)
{
_objs.Add(new ObjToWeigh(rng.Next(200), rng.Next(200), rng.Next(200)));
}
}
[Benchmark]
public int TotalWeight()
{
int tot = 0;
foreach (var o in _objs)
tot += o.Metric1;
return tot;
}
[Benchmark]
public int TotalWeightByField_or_Prop()
{
const string propName = "Metric1";
var propInfo = typeof(ObjToWeigh).GetProperty(propName);
var fieldInfo = typeof(ObjToWeigh).GetField(propName);
if (propInfo == null && fieldInfo == null)
throw new Exception($"Invalid property {propName}");
int tot = 0;
foreach (var o in _objs)
{
if (propInfo != null)
tot += (int)propInfo.GetValue(o);
else
tot += (int)fieldInfo.GetValue(o);
}
return tot;
}
[Benchmark]
public int TotalWeightByField()
{
const string propName = "Metric1";
var fieldInfo = typeof(ObjToWeigh).GetField(propName);
if (fieldInfo == null)
throw new Exception($"Invalid field {propName}");
int tot = 0;
foreach (var o in _objs)
{
tot += (int)fieldInfo.GetValue(o);
}
return tot;
}
}
public class ObjToWeigh
{
public int Metric1;
public int Metric2;
public int Metric3;
public ObjToWeigh(int m1, int m2, int m3)
{
Metric1 = m1;
Metric2 = m2;
Metric3 = m3;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment