Repository navigation
Improve LoadMultipleUpdatesRows performance. - #6588
Conversation
|
Hi @lauxjpn! Were you waiting on others' input before wanting this merged? If it's ready, let me know. |
|
@nbrady-techempower From my point of view it can be merged. But we should probably wait for @roji to confirm, that we either don't have to run this first on the ASP.NET benchmarking server, or that they did and are fine with the change. |
|
#5933 uses LINQ because code using EF Core is very likely to also use LINQ, a very common, real-world scenario (unlike Platform/Raw test code). On another note, this PR seems to do less work: it doesn't make sure that RandomNumber is set to a new, different value. Even if it always passes verification, I'd like to ask @nbrady-techempower to please clarify: does the RandomNumber have to be updated to a different value or is it OK if it's occasionally set to the same (remains unchanged)? |
It seems to be an imprecise wording in the specs, since virtually every other framework benchmark (including the non-EF ASP.NET Core ones) implement it just by running a simple random generator and using whatever it returns (e.g. see the PHP implementation). The term "unique" in this case is not really meant as unique within some kind of scope. It can't be, because it does not state what the scope is: unique within a web request, unique within all concurrent web requests, etc. The specs just want to express, that randomly generated numbers should be used and that individual
The remaining ID deduplication code that still exists in this PR is really just something EF Core specific in regards to the specifications and it does not really have anything directly to do with the actual test. It only exists, because the requirements just want you to generate UPDATE statements for random IDs. EF Core only tracks a single instance of an entity within a single context at a time. So if for pure coincidence, the random number generator generates the same ID within a web request, which is fine/expected for the requirements of the benchmark, EF Core is basically "too clever" and only emits the So the remaining ID deduplication code only exists because of the (artificial) requirement, that the IDs have to be random and that if two changes are made to the same entity, two The main point here is, that a user would never write random ID deduplication code in the first place. We just need it here for our special EF Core case in regards to the specification. So it should not matter, whether this is being written using LINQ, or anything else. On the contrary, we should keep this particular oddity as fast as possible, to keep the benchmark as comparable to other frameworks as possible (which don't have to implement this code in the first place). |
|
Here are run results for this change. tl;dr this doesn't seem to bring a noticeable change either way; my guess is that the overhead of using HashSet (non-trivial data structure, hash calculations...) offsets gains etc.
Detailed run resultsBaseline before changesfix/aspnetcore_ef_updatetest/aspnetcore_ef_update_2test/aspnetcore_ef_update_3Scenario definition multiple_query_aspnet:
db:
job: postgresql
application:
job: aspnet
source:
dockerFile: frameworks/CSharp/aspnetcore/aspcore-mw-ef-pg.dockerfile
dockerImageName: aspcore-mw-ef-pg
load:
job: wrk
variables:
presetHeaders: html
path: /queries/ef?queries=
serverPort: 8080 |
|
BTW forgot to mention that I executed the above on PostgreSQL. |
@n-stefan Right now, the verification only cares that an update is made. We'll do a code review to make sure there is random number generation, but the toolset is counting updates. If, for some reason, your framework won't pass the update along if the value ends up being the same, you could fail and that's why some frameworks have to make sure it's a random number that hasn't been used before. That's not an official requirement, but seems necessary for some. |
|
I see, thank you. |
|
@roji Thanks for running, but this PR is about the The TFB would run this with the following command (made explicit here to remove any remaining ambiguity): |
|
@lauxjpn
If RandomNumber is set to the same value, will EF Core: |
|
@n-stefan It is the first one (it will just update it anyway). I tested it before removing the code, because I was unsure about it as well. This is the code I used for verification (it's always good to double check, so feel encouraged to run and verify it): Program.csusing System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace IssueConsoleTemplate
{
public class IceCream
{
public int IceCreamId { get; set; }
public string Name { get; set; }
}
public class Context : DbContext
{
public DbSet<IceCream> IceCreams { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
const string connectionString = @"Data Source=.\MSSQL14;Integrated Security=SSPI;Initial Catalog=Performance_001";
optionsBuilder.UseSqlServer(connectionString)
.UseLoggerFactory(
LoggerFactory.Create(
configure => configure
.AddConsole()
.AddFilter(level => level >= LogLevel.Information)))
.EnableSensitiveDataLogging()
.EnableDetailedErrors();
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<IceCream>(
entity =>
{
entity.HasData(
new IceCream {IceCreamId = 1, Name = "Vanilla"});
});
}
}
internal static class Program
{
private static void Main()
{
using var context = new Context();
context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
context.ChangeTracker.AutoDetectChangesEnabled = false;
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var iceCream1 = context.IceCreams.AsNoTracking().First();
iceCream1.Name = "Vanilla"; // same name, so no change (could be omitted)
context.Entry(iceCream1).State = EntityState.Modified; // this is enough to trigger an UPDATE statement
context.SaveChanges();
}
}
}The output is: Executed DbCommand (33ms) [Parameters=[@p1='1', @p0='Vanilla' (Size = 4000)], CommandType='Text', CommandTimeout='30']
SET NOCOUNT ON;
UPDATE [IceCreams] SET [Name] = @p0
WHERE [IceCreamId] = @p1;
SELECT @@ROWCOUNT;BTW, I did not test, whether setting the value to the entity property itself (what this PR does) or to the EF Core |
|
In that case it's fine :) |
Oh sorry, my bad - I somehow managed to miss that :/ I'll rerun for the right scenario. |
|
@lauxjpn it seems like the repo is currently missing an aspcore-mw-ef-pg-up.dockerfile; aspcore-mw-ef-pg.dockerfile omits the update scenario. IIRC we have different app images for updates because the connection string is different for update and for the other scenarios (we probably need to revisit it following recent PG multiplexing/connection string changes). Did your command-line from here work? Trying to run it errored with Do you want to submit a PR adding a aspcore-mw-ef-pg-up.dockerfile, just like for the non-EF scenarios? You could also add it in your branch so we don't have to wait for this to be merged. However, it would be good to have a separate commit only doing that (so I could run it as a baseline), and then the actual change commits based on top of that. Let me know - I'm ready to do any additional runs you need. |
|
@roji Ah shoot, I forgot it was recently removed in #6568. Since the MySQL stuff isn't merged yet, I think only SQL Server could run it at the moment. (Locally, I am still on the last commit that had PG support, for comparison.) I'll add the Postgres related stuff to the commit in a dedicated feature branch on my fork and link it here, so it can be used for testing this PR (it has the highest RPS, so it should show any improvements with the least noise). |
|
Sure thing - whatever works. Just point me at some commits. |
|
@roji The 3 variations in the same order as before, including the reverted commit that removed the Npgsql update benchmarks, are available at:
The TFB command posted before should work fine now. |
|
@lauxjpn here are the run results. Please verify the commit hashes/command-lines below - it's easy to get something wrong (i.e. trust nobody/nothing when it comes to perf...). The changes below seem small enough to be generally variance/noise.
Before any changestest/aspnetcore_ef_update_1test/aspnetcore_ef_update_2test/aspnetcore_ef_update_3ASP.NET scenario config multiple_update_aspnet:
db:
job: postgresql
application:
job: aspnet
source:
dockerFile: frameworks/CSharp/aspnetcore/aspcore-mw-ef-pg-up.dockerfile
dockerImageName: aspcore-mw-ef-pg-up
load:
job: wrk
variables:
presetHeaders: html
path: /updates/ef?queries=
serverPort: 8080 |
Yes, the gain is small in comparison to disk write operations, so its difficult to measure accurately without running these benchmarks many times. Therefore, I ran the variations independent of the TFB with Benchmark.NET. They are grouped by query level and sorted from best to worst: Benchmark.NET results
Program.csusing System;
using System.Collections.Generic;
using System.Linq;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
namespace IssueConsoleTemplate
{
public class World
{
public int Id { get; set; }
public int RandomNumber { get; set; }
}
[MemoryDiagnoser]
public class Benchmarks
{
private static readonly Random _random = new Random(42);
private static readonly World[] _data = Enumerable.Range(1, 10_001)
.Select(n => new World {Id = n, RandomNumber = _random.Next(1, 10_001)})
.ToArray();
private readonly Func<int, World> _firstWorldTrackedQuery = id => _data[id - 1];
[Params(1, 5, 10, 15, 20)]
public int QueryLevels { get; set; }
[Benchmark]
public void Baseline(/*int count*/)
{
var count = QueryLevels;
var results = new World[count];
int currentValue, newValue;
var ids = Enumerable.Range(1, 10000).Select(x => _random.Next(1, 10001)).Distinct().Take(count).ToArray();
for (var i = 0; i < count; i++)
{
results[i] = /*await */_firstWorldTrackedQuery(/*_dbContext, */ids[i]);
currentValue = results[i].RandomNumber;
do
{
newValue = _random.Next(1, 10001);
}
while (newValue == currentValue);
results[i].RandomNumber = newValue;
// _dbContext.Entry(results[i]).State = EntityState.Modified;
}
// await _dbContext.SaveChangesAsync();
// return results;
}
[Benchmark]
public void Update_1(/*int count*/)
{
var count = QueryLevels;
var results = new World[count];
var usedIds = new HashSet<int>(count);
for (var i = 0; i < count; i++)
{
int id;
do
{
id = _random.Next(1, 10001);
} while (!usedIds.Add(id));
results[i] = /*await */_firstWorldTrackedQuery(/*_dbContext, */id);
results[i].RandomNumber = _random.Next(1, 10001);
// _dbContext.Entry(results[i]).State = EntityState.Modified;
}
// await _dbContext.SaveChangesAsync();
// return results;
}
[Benchmark]
public void Update_2(/*int count*/)
{
var count = QueryLevels;
var results = new World[count];
using var ids = Enumerable.Repeat(0, int.MaxValue)
.Select(_ => _random.Next(1, 10001))
.Distinct()
.Take(count)
.GetEnumerator();
for (var i = 0; i < count; i++)
{
ids.MoveNext();
results[i] = /*await */_firstWorldTrackedQuery(/*_dbContext, */ids.Current);
results[i].RandomNumber = _random.Next(1, 10001);
// _dbContext.Entry(results[i]).State = EntityState.Modified;
}
// await _dbContext.SaveChangesAsync();
// return results;
}
[Benchmark]
public void Update_3(/*int count*/)
{
var count = QueryLevels;
var results = new World[count];
for (var i = 0; i < count; i++)
{
int id;
do
{
id = _random.Next(1, 10001);
} while (results.Take(i).Any(r => r.Id == id));
results[i] = /*await */_firstWorldTrackedQuery(/*_dbContext, */id);
results[i].RandomNumber = _random.Next(1, 10001);
// _dbContext.Entry(results[i]).State = EntityState.Modified;
}
// await _dbContext.SaveChangesAsync();
// return results;
}
}
internal static class Program
{
private static void Main()
{
#if DEBUG
var benchmarks = new Benchmarks();
try
{
benchmarks.QueryLevels = 2;
benchmarks.Setup();
benchmarks.Baseline();
benchmarks.Update_1();
benchmarks.Update_2();
benchmarks.Update_3();
}
finally
{
benchmarks.CleanUp();
}
#else
BenchmarkRunner.Run<Benchmarks>();
#endif
}
}
}Full summaryThe Also, for the |
I did do some pretty long runs... but as you say, the update test actually does disk activity (unlike other benchmarks which most probably only read data cached in memory). In any case, your BDN results seem pretty conclusive... Thanks! |
|
This benchmark isn't run currently, is it? |
|
For Npgsql, it is not since #6568 (comment). |
|
Right, there are runs only up to May 2.
Both using the old connection string. |
This PR reverts some of the changes made in #5933. It improves performance and reduces the amount of memory allocations in number and size.
It increases the throughput of the
LoadMultipleUpdatesRows()method on my local machine running the vagrant VM (altered to use 6 CPU cores and 20 GB of RAM) by up to 2%.The main issue for EF Core here is of course, that while we could retrieve two untracked entities with the same ID (which could happen by shear coincidence through the (pseudo) random number generator), we can only effectively update one of those entities within one
SaveChanges()call.The implementation of this PR uses an explicit
HashSet<>to ensure, that no duplicate random ID numbers are being used for querying. The advantage over the previous algorithm is, that it is faster than the LINQ query and it does not unnecessarily allocate an array (as the previous algorithm did at the end withToArray()). While theHashSet<>implementation uses 56 bytes and the internalSet<>implementation used byDistinct()(part of the previous algorithm) uses only 24 bytes, we should still allocate fewer bytes over all with explicitly usingHashSet<>. Also, we can set the capacity in advance this way.There are two possible variations of this for possible future optimizations:
One is to keep using the old algorithm for this part, just drop the
ToArray()call and use the returned enumerator when in need for a distinct ID later. This should save additional memory (the difference between theHashSet<>and theSetimplementation in bytes) at the cost of CPU cycles.This is slower than this PR on my local rig.
If anybody wants to test this variation, it's available through a feature branch of my fork: https://github.com/lauxjpn/FrameworkBenchmarks/tree/test/aspnetcore_ef_update_2
The other is to not use any explicit set at all and just trade memory for CPU cycles in general, by iterating over the already queried
results[]array for duplicate ID detection (which could be worth it, since the number of array items is pretty small).This slower than the previous variation on my local rig.
If anybody wants to test this variation, it's available through a feature branch of my fork: https://github.com/lauxjpn/FrameworkBenchmarks/tree/test/aspnetcore_ef_update_3
Since #6566, I am now unsure what the correct process for this PR is, since it is targeting ASP.NET.
@roji Is the special standard of #6566 only meant for the ASP.NET Core platform benchmarks and does therefore not apply to the normal ASP.NET Core benchmarks like this one, or does it apply to all ASP.NET Core benchmarks, or only to specific files (e.g. those that could affect Npgsql/PostgreSQL benchmarks)?