Entity Framework Core 2 Vs Dapper Performance Benchmark

Originally published on mmohsin.com.

Motivation:

Okay, i know that you have seen other benchmarks on the internet showing dapper is faster than Entity Framework. I found it unfair to compare an auto-generated SQL to the one written by a good developer, so decided to benchmark it on equal basis.

Source Code:

You can download the source code from git.

Test Environment:

  1. A SQL database server which is on LAN
  2. A table containing 500k rows and 50 columns.
  3. .Net Core 2 Console Application.

Nugets:

  1. Benchmark.NET
  2. Dapper
  3. Entity Framework Core 2

Use Case:

  • Fetching 5000 rows out of 500k rows.

Dapper.Net Repository

Dapper’s query looks like this.

public class DapperRepository
{
public List GetUsersWithDapper()
{
using (IDbConnection db = new SqlConnection(@"YourConnectionString"))
{
return db.Query
($"select top 5000 * from users_general").ToList();
}
}
}

Entity Framework Core 2 Repository

public class EFRepository
{
public List GetUsersWithEF()
{
using (var db = new EFCore2TestContext())
{
return db.UsersGeneral.FromSql("Select top 5000 * from users_general").AsNoTracking().ToList();
//return db.UsersGeneral.Take(5000).AsNoTracking().ToList();
}
}
}

Notice that i used AsNoTracking() for performance hit. As it will indicate EF not to track the models for change.

Benchmark Class

public class EFCore2VsDapper
{
EFRepository _EFRepo;
DapperRepository _DapperRepo;
ADORepository _adoRepository;

public EFCore2VsDapper()
{
_EFRepo = new EFRepository();
_DapperRepo = new DapperRepository();
_adoRepository = new ADORepository();
}

[Benchmark]
public List GetUsersWithEntityFramework() => _EFRepo.GetUsersWithEF();

[Benchmark]
public List GetUsersWithDapper() => _DapperRepo.GetUsersWithDapper();

//[Benchmark] Uncomment if you want to add ADO.NET to the competition
//public List GetUsersWithADO() => _adoRepository.GetUsersWithADO();
}

Run It!

class Program
{
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run(typeof(EFCore2VsDapper));

Console.WriteLine("Done");
Console.ReadLine();
}
}

Results:

For fetching 5000 rows out of 500k, Entity Framework Core 2 outperformed dapper. It was hard for me to believe it initially so i ran the test several times. Same results.

Conclusion:

Above results doesn’t mean that one is better in performance than the other, the above test was run for a very specific use case i-e fetching rows, passing plain query and using AsNoTracking(). Things can change for insert, update and especially when the EF context grows.

So, don’t select either based on my benchmark. You can download the source code and it is highly recommended to test it yourself for different scenarios before making a decision.

I’m missing something? or your tests gave different results? let me know by sharing your valuable feedback.

Thanks for reading. If you found this article useful, feel free to hit that clap button 👏 to help others find it.