Skip to content

Instantly share code, notes, and snippets.

@OlegKarasik
Created October 28, 2019 11:59
Show Gist options
  • Save OlegKarasik/d641bb34e8da662fde9cb83eb765fdad to your computer and use it in GitHub Desktop.
Save OlegKarasik/d641bb34e8da662fde9cb83eb765fdad to your computer and use it in GitHub Desktop.
What is wrong with this code? Part 2.
using System;
using System.Collections.Generic;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
namespace Application
{
public sealed class Query
{
public readonly string StringValue;
public readonly int IntValue;
public Query(
string stringValue,
int intValue)
{
this.StringValue = stringValue;
this.IntValue = intValue;
}
}
public sealed class Metadata
{
public readonly string StringCriteria;
public readonly int IntCriteria;
public Metadata(
string stringCriteria,
int intCriteria)
{
this.StringCriteria = stringCriteria;
this.IntCriteria = intCriteria;
}
}
public sealed class Optimization
{
public Query Query;
public bool Evaluate(Metadata metadata)
{
return metadata.StringCriteria == this.Query.StringValue ||
metadata.IntCriteria == this.Query.IntValue;
}
}
[MemoryDiagnoser, RPlotExporter, RankColumn]
public class BenchmarkClass
{
private readonly int batchSize;
private readonly Query query;
private readonly List<Metadata> metadata;
public BenchmarkClass()
{
this.batchSize = 100;
this.query = new Query("One", 1);
this.metadata = new List<Metadata>(9)
{
new Metadata("One", 1),
new Metadata("Two", 2),
new Metadata("Three", 3),
new Metadata("Four", 4),
new Metadata("One", 5),
new Metadata("Six", 6),
new Metadata("Seven", 1),
new Metadata("Eight", 8),
new Metadata("Nine", 9),
};
}
[Benchmark(Baseline = true)]
public void BatchFindAll()
{
for (var i = 0; i < this.batchSize; ++i)
{
_ = this.metadata.FindAll(
m => m.StringCriteria == this.query.StringValue ||
m.IntCriteria == this.query.IntValue);
}
}
[Benchmark]
public void BatchFindAllOptimized()
{
var optimization = new Optimization();
var predicate = new Predicate<Metadata>(optimization.Evaluate);
for (var i = 0; i < this.batchSize; ++i)
{
optimization.Query = this.query;
_ = this.metadata.FindAll(predicate);
}
}
[Benchmark]
public void Allocations()
{
for (var i = 0; i < this.batchSize; ++i)
{
var list = new List<Metadata>();
list.Add(this.metadata[0]); // #1
list.Add(this.metadata[4]); // #5
list.Add(this.metadata[6]); // and #7
}
}
}
internal class Program
{
private static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<BenchmarkClass>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment