Skip to content

Instantly share code, notes, and snippets.

@ptupitsyn
Last active September 14, 2020 08:45
Show Gist options
  • Save ptupitsyn/e62a334421de053c44fa1b1e35a2de28 to your computer and use it in GitHub Desktop.
Save ptupitsyn/e62a334421de053c44fa1b1e35a2de28 to your computer and use it in GitHub Desktop.
Dapper vs EF Core on Sqlite In-Memory
using Microsoft.EntityFrameworkCore;
namespace DapperVsEf
{
public class BenchContext : DbContext
{
public BenchContext(DbContextOptions options) : base(options)
{
}
public DbSet<Person> Persons { get; set; }
}
}
using System;
using System.Linq;
using BenchmarkDotNet.Attributes;
using Microsoft.Data.Sqlite;
using Dapper;
using Microsoft.EntityFrameworkCore;
namespace DapperVsEf
{
/// <summary>
/// | Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated |
/// |------------ |---------:|---------:|---------:|------:|------:|------:|----------:|
/// | QueryDapper | 528.4 us | 8.70 us | 7.71 us | - | - | - | 64.06 KB |
/// | QueryEf | 516.4 us | 19.11 us | 52.64 us | - | - | - | 155.21 KB |
/// </summary>
[MemoryDiagnoser]
public class Benches
{
private static readonly SqliteConnection Connection = GetInMemoryOpenSqliteConnection();
private static readonly BenchContext Context = GetDbContext();
[Benchmark]
public void QueryDapper()
{
var res = Connection.Query<Person>("SELECT Id, Name FROM Persons WHERE ID > 500").ToList();
if (res.Count != 500)
{
throw new Exception();
}
}
[Benchmark]
public void QueryEf()
{
var res = Context.Persons.Where(p => p.Id > 500).ToList();
if (res.Count != 500)
{
throw new Exception();
}
}
private static SqliteConnection GetInMemoryOpenSqliteConnection()
{
var sqliteConnection = new SqliteConnection("Data Source=:memory:;");
// Connection must be open otherwise schema does not get created.
sqliteConnection.Open();
return sqliteConnection;
}
private static BenchContext GetDbContext()
{
var options = new DbContextOptionsBuilder<BenchContext>()
.UseSqlite(Connection)
.Options;
var res = new BenchContext(options);
res.Database.EnsureCreated();
res.Persons.AddRange(Enumerable.Range(1, 1000).Select(x => new Person {Id = x, Name = "Person " + x}));
res.SaveChanges();
return res;
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.12.1" />
<PackageReference Include="Dapper" Version="2.0.35" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="3.1.4" />
</ItemGroup>
</Project>
namespace DapperVsEf
{
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
}
using BenchmarkDotNet.Running;
namespace DapperVsEf
{
class Program
{
static void Main(string[] args)
{
BenchmarkRunner.Run<Benches>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment