The default batch size in Entity Framework is 42 (for the SQL Server provider) but it’s good to try different variations of this to see what works best your specific scenario.
BenchmarkDotNet is very useful here but ideally we wouldn’t have to create multiple DbContext classes each with a different batch size to test things. This is possible if we modify our DbContext to allow setting of the batch size upon construction…
We can now use our new constructor in combination with the Params attribute in BenchmarkDotNet to test different batch sizes in the same run. The Params attribute tells BenchmarkDotNet to run all the benchmarks present in the class once for each param value.
Lines 19 and 20 below have all the different batch sizes we want to benchmark and in line 33 we pass the current batch size value into the BloggingContext constructor…
Output from a run of the above benchmark is below.
Click on the image for a larger view in a new tab…
This benchmark was run using Entity Framework 7 Preview 6 on a remote DB but which was in the same Azure region as the benchmark app so latency would have been low. We can see in this case the ideal batch size seems to be 200.
2 thoughts on “Benchmark different batch sizes in Entity Framework using BenchmarkDotNet”
The benchmark is missing a case for the default batch size in Entity Framework is 42.
42 will be similar enough to 50 which is there. The trick is to 50 the amount that’s not too high or too low to give the right performance.