Skip to content

Instantly share code, notes, and snippets.

@DanielLoth
Created October 3, 2017 04:22
Show Gist options
  • Save DanielLoth/f0dd3522734c59d5e324f8df22e9fa14 to your computer and use it in GitHub Desktop.
Save DanielLoth/f0dd3522734c59d5e324f8df22e9fa14 to your computer and use it in GitHub Desktop.
Benchmarking Dapper data access - Dynamic vs Expando vs POCO
using BenchmarkDotNet.Attributes;
using Dapper;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Dynamic;
using System.Linq;
namespace Benchmarks.Benchmarks
{
public class DapperBenchmarks
{
public static readonly int N = 10;
public static readonly string Query = "select * from Forms.DocumentType";
public static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
/*
// * Summary *
Host Process Environment Information:
BenchmarkDotNet.Core=v0.9.9.0
OS=Microsoft Windows NT 6.1.7601 Service Pack 1
Processor=Intel(R) Core(TM) i7-3770 CPU 3.40GHz, ProcessorCount=8
Frequency=3312832 ticks, Resolution=301.8565 ns, Timer=TSC
CLR=MS.NET 4.0.30319.42000, Arch=32-bit RELEASE
GC=Concurrent Workstation
JitModules=clrjit-v4.6.1590.0
Type=DapperBenchmarks Mode=Throughput
Method | Median | StdDev |
-------------------- |---------- |---------- |
ResultsAsPoco | 3.4205 ms | 0.0520 ms |
ResultsAsDynamic | 3.4276 ms | 0.1595 ms |
ResultsAsDictionary | 6.0761 ms | 0.6618 ms |
// ***** BenchmarkRunner: End *****
Global total time: 00:00:39 (39.08 sec)
*/
[Benchmark]
public void ResultsAsPoco()
{
using (var con = new SqlConnection(ConnectionString))
{
for (var i = 0; i < N; i++)
{
var results = con.Query<Poco>(Query).AsList();
if (results.Count == 0)
{
throw new Exception();
}
}
}
}
[Benchmark]
public void ResultsAsDynamic()
{
using (var con = new SqlConnection(ConnectionString))
{
for (var i = 0; i < N; i++)
{
var results = con.Query<dynamic>(Query).AsList();
if (results.Count == 0)
{
throw new Exception();
}
}
}
}
[Benchmark]
public void ResultsAsDictionary()
{
using (var con = new SqlConnection(ConnectionString))
{
for (var i = 0; i < N; i++)
{
var results = con.Query<dynamic>(Query).Select(x => ToExpandoObject(x)).AsList();
if (results.Count == 0)
{
throw new Exception();
}
}
}
}
public static IDictionary<string, object> ToExpandoObject(object value)
{
IDictionary<string, object> dapperRowProperties = value as IDictionary<string, object>;
IDictionary<string, object> expando = new ExpandoObject();
foreach (KeyValuePair<string, object> property in dapperRowProperties)
expando.Add(property.Key, property.Value);
return expando as ExpandoObject;
}
private class Poco
{
public int DocumentTypeID { get; set; }
public string DocumentTypeCode { get; set; }
public string DocumentTypeNameFormat { get; set; }
public int? CreatedForFormId { get; set; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment