Skip to content

Instantly share code, notes, and snippets.

@davepcallan
Created November 25, 2025 15:49
Show Gist options
  • Select an option

  • Save davepcallan/62a84365b6c1a001091780c1e43f05d9 to your computer and use it in GitHub Desktop.

Select an option

Save davepcallan/62a84365b6c1a001091780c1e43f05d9 to your computer and use it in GitHub Desktop.
Sample benchmark to test different Entity Framework batch sizes with the SQL Server provider
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Columns;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Reports;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
namespace EntityFrameworkBenchmarks;
[Config(typeof(Config))]
public class BatchSizeBenchmark
{
[Params(1000)]
public int records;
[Params(50, 100, 150, 200)]
public int batchSize;
[GlobalSetup]
public void GlobalSetup()
{
using var context = new BloggingContext();
// context.Database.EnsureDeleted(); *** Careful ***
context.Database.EnsureCreated();
}
[Benchmark]
public async Task InsertRows()
{
var db = new BloggingContext(batchSize);
for (var i = 0; i < records; i++)
{
var blog = new Blog { Name = "Foo" + i, Url = "Bar" + i };
db.Blogs.Add(blog);
}
await db.SaveChangesAsync();
}
private class Config : ManualConfig
{
public Config()
{
SummaryStyle =
SummaryStyle.Default
.WithRatioStyle(RatioStyle.Trend)
.WithTimeUnit(Perfolizer.Horology.TimeUnit.Millisecond);
}
}
}
public class BloggingContext : DbContext
{
private int _batchSize;
public BloggingContext(int batchSize = 42)
{
_batchSize = batchSize;
}
public DbSet<Blog> Blogs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseSqlServer(
@"Server=localhost;Database=efsamples;Trusted_Connection=True;TrustServerCertificate=true",
optionsBuilder => optionsBuilder.MaxBatchSize(_batchSize));
}
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public int Rating { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment