Skip to content
This repository was archived by the owner on Mar 24, 2026. It is now read-only.

Improve LoadMultipleUpdatesRows performance. - #6588

Merged
NateBrady23 merged 1 commit into
TechEmpower:masterfrom
lauxjpn:fix/aspnetcore_ef_update
May 25, 2021
Merged

NateBrady23 merged 1 commit into
TechEmpower:masterfrom
lauxjpn:fix/aspnetcore_ef_update

Conversation

@lauxjpn

@lauxjpn lauxjpn commented May 14, 2021 •

Copy link
Copy Markdown
Contributor

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 with ToArray()). While the HashSet<> implementation uses 56 bytes and the internal Set<> implementation used by Distinct() (part of the previous algorithm) uses only 24 bytes, we should still allocate fewer bytes over all with explicitly using HashSet<>. 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 the HashSet<> and the Set implementation 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)?

@NateBrady23

Copy link
Copy Markdown
Member

Hi @lauxjpn! Were you waiting on others' input before wanting this merged? If it's ready, let me know.

@lauxjpn

lauxjpn commented May 19, 2021

Copy link
Copy Markdown
Contributor Author

@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.

@n-stefan

Copy link
Copy Markdown
Contributor

#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)?

@lauxjpn

lauxjpn commented May 21, 2021

Copy link
Copy Markdown
Contributor Author

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 UPDATE statements need to be run (so that nobody takes a shortcut or can try to profit from running the same update statement using the same ID over and over again).


#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).

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 UPDATE statement for the last change to the entity. The table result would be the same as with other benchmarks that just execute duplicated UPDATE statements, but we would violate the specs because one fewer UPDATE statement was send than required.

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 UPDATE statements have to be send. Other frameworks don't have this EF Core optimization, so they do not need to work around it as we do.

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).

@roji

roji commented May 21, 2021 •

Copy link
Copy Markdown
Contributor

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.

Config RPS
Baseline before changes 229,117
fix/aspnetcore_ef_update 229,459
test/aspnetcore_ef_update_2 230,313
test/aspnetcore_ef_update_3 225,275
Detailed run results

Baseline before changes

dotnet run --config Z:\projects\AspNetBenchmarks\scenarios\te.benchmarks.yml --scenario multiple_query_aspnet --profile aspnet-citrine-lin --application.source.repository https://github.com/lauxjpn/FrameworkBenchmarks --application.source.branchOrCommit fix/aspnetcore_ef_update#59753a998951f07fbc933d85019f60b4b405864e --application.framework net6.0 --variable warmup=60 --duration=120

| db                  |         |
| ------------------- | ------- |
| CPU Usage (%)       | 24      |
| Cores usage (%)     | 665     |
| Working Set (MB)    | 46      |
| Build Time (ms)     | 1,749   |
| Start Time (ms)     | 333     |
| Published Size (KB) | 914,035 |


| application         |         |
| ------------------- | ------- |
| CPU Usage (%)       | 98      |
| Cores usage (%)     | 2,754   |
| Working Set (MB)    | 434     |
| Build Time (ms)     | 3,372   |
| Start Time (ms)     | 477     |
| Published Size (KB) | 217,432 |


| load                   |           |
| ---------------------- | --------- |
| CPU Usage (%)          | 14        |
| Cores usage (%)        | 380       |
| Working Set (MB)       | 37        |
| Private Memory (MB)    | 358       |
| Start Time (ms)        | 0         |
| First Request (ms)     | 1,180     |
| Requests/sec           | 229,117   |
| Requests               | 3,459,574 |
| Mean latency (ms)      | 1.33      |
| Max latency (ms)       | 44.65     |
| Bad responses          | 0         |
| Socket errors          | 0         |
| Read throughput (MB/s) | 34.47     |
| Latency 50th (ms)      | 1.07      |
| Latency 75th (ms)      | 1.29      |
| Latency 90th (ms)      | 1.53      |
| Latency 99th (ms)      | 10.27     |

fix/aspnetcore_ef_update

dotnet run --config Z:\projects\AspNetBenchmarks\scenarios\te.benchmarks.yml --scenario multiple_query_aspnet --profile aspnet-citrine-lin --application.source.repository https://github.com/lauxjpn/FrameworkBenchmarks --application.source.branchOrCommit fix/aspnetcore_ef_update#e906e65c4f7607c55d824af1f1f845aa98084e6b --application.framework net6.0 --variable warmup=60 --duration=120

| db                  |         |
| ------------------- | ------- |
| CPU Usage (%)       | 24      |
| Cores usage (%)     | 673     |
| Working Set (MB)    | 46      |
| Build Time (ms)     | 1,891   |
| Start Time (ms)     | 352     |
| Published Size (KB) | 914,035 |


| application         |         |
| ------------------- | ------- |
| CPU Usage (%)       | 98      |
| Cores usage (%)     | 2,739   |
| Working Set (MB)    | 436     |
| Build Time (ms)     | 15,358  |
| Start Time (ms)     | 460     |
| Published Size (KB) | 217,431 |


| load                   |           |
| ---------------------- | --------- |
| CPU Usage (%)          | 14        |
| Cores usage (%)        | 383       |
| Working Set (MB)       | 38        |
| Private Memory (MB)    | 358       |
| Start Time (ms)        | 0         |
| First Request (ms)     | 1,199     |
| Requests/sec           | 229,459   |
| Requests               | 3,464,777 |
| Mean latency (ms)      | 1.33      |
| Max latency (ms)       | 41.38     |
| Bad responses          | 0         |
| Socket errors          | 0         |
| Read throughput (MB/s) | 34.53     |
| Latency 50th (ms)      | 1.07      |
| Latency 75th (ms)      | 1.29      |
| Latency 90th (ms)      | 1.54      |
| Latency 99th (ms)      | 10.06     |

test/aspnetcore_ef_update_2

dotnet run --config Z:\projects\AspNetBenchmarks\scenarios\te.benchmarks.yml --scenario multiple_query_aspnet --profile aspnet-citrine-lin --application.source.repository https://github.com/lauxjpn/FrameworkBenchmarks --application.source.branchOrCommit test/aspnetcore_ef_update_2#2a29ef68dff7f561fb04a52bcf55974a4974bf63 --application.framework net6.0 --variable warmup=60 --duration=120

| load                   |           |
| ---------------------- | --------- |
| CPU Usage (%)          | 14        |
| Cores usage (%)        | 383       |
| Working Set (MB)       | 37        |
| Private Memory (MB)    | 358       |
| Start Time (ms)        | 0         |
| First Request (ms)     | 1,230     |
| Requests/sec           | 230,313   |
| Requests               | 3,477,671 |
| Mean latency (ms)      | 1.27      |
| Max latency (ms)       | 32.92     |
| Bad responses          | 0         |
| Socket errors          | 0         |
| Read throughput (MB/s) | 34.65     |
| Latency 50th (ms)      | 1.07      |
| Latency 75th (ms)      | 1.29      |
| Latency 90th (ms)      | 1.50      |
| Latency 99th (ms)      | 8.43      |

test/aspnetcore_ef_update_3

dotnet run --config Z:\projects\AspNetBenchmarks\scenarios\te.benchmarks.yml --scenario multiple_query_aspnet --profile aspnet-citrine-lin --application.source.repository https://github.com/lauxjpn/FrameworkBenchmarks --application.source.branchOrCommit test/aspnetcore_ef_update_3#66a5ce8957bb24899b97aba274e782ce9848f3be --application.framework net6.0 --variable warmup=60 --duration=120

| db                  |         |
| ------------------- | ------- |
| CPU Usage (%)       | 24      |
| Cores usage (%)     | 670     |
| Working Set (MB)    | 47      |
| Build Time (ms)     | 1,717   |
| Start Time (ms)     | 348     |
| Published Size (KB) | 914,035 |


| application         |         |
| ------------------- | ------- |
| CPU Usage (%)       | 99      |
| Cores usage (%)     | 2,758   |
| Working Set (MB)    | 434     |
| Build Time (ms)     | 15,456  |
| Start Time (ms)     | 488     |
| Published Size (KB) | 217,431 |


| load                   |           |
| ---------------------- | --------- |
| CPU Usage (%)          | 13        |
| Cores usage (%)        | 377       |
| Working Set (MB)       | 38        |
| Private Memory (MB)    | 358       |
| Start Time (ms)        | 0         |
| First Request (ms)     | 1,186     |
| Requests/sec           | 225,275   |
| Requests               | 3,401,581 |
| Mean latency (ms)      | 1.31      |
| Max latency (ms)       | 36.57     |
| Bad responses          | 0         |
| Socket errors          | 0         |
| Read throughput (MB/s) | 33.90     |
| Latency 50th (ms)      | 1.09      |
| Latency 75th (ms)      | 1.31      |
| Latency 90th (ms)      | 1.56      |
| Latency 99th (ms)      | 9.09      |
Scenario 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

@roji

roji commented May 21, 2021

Copy link
Copy Markdown
Contributor

BTW forgot to mention that I executed the above on PostgreSQL.

@NateBrady23

Copy link
Copy Markdown
Member

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)?

@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.

@n-stefan

Copy link
Copy Markdown
Contributor

I see, thank you.

@lauxjpn

lauxjpn commented May 21, 2021

Copy link
Copy Markdown
Contributor Author

@roji Thanks for running, but this PR is about the EfDb.LoadMultipleUpdatesRows() method, so its about the update type.
Postgres is fine though (whatever has the most RPS should run it).

The TFB would run this with the following command (made explicit here to remove any remaining ambiguity):

tfb --test aspcore-mw-ef-pg-up --type update --mode benchmark

@n-stefan

Copy link
Copy Markdown
Contributor

@lauxjpn
This is the part I'm not sure about:

results[i].RandomNumber = _random.Next(1, 10001);
_dbContext.Entry(results[i]).State = EntityState.Modified;

If RandomNumber is set to the same value, will EF Core:
1.See that the entity state is Modified and emit the UPDATE.
Or
2.See that the entity state is Modified but detect that RandomNumber hasn't actually changed and skip emitting the UPDATE, resulting in verification failure.

@lauxjpn

lauxjpn commented May 22, 2021 •

Copy link
Copy Markdown
Contributor Author

@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.cs
using 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 CurrentValue (what earlier PRs did) is faster. But setting it to the actual entity property felt much more natural and common, so I choose it for that reason.

@n-stefan

Copy link
Copy Markdown
Contributor

In that case it's fine :)

@roji

roji commented May 22, 2021

Copy link
Copy Markdown
Contributor

Thanks for running, but this PR is about the EfDb.LoadMultipleUpdatesRows() method, so its about the update type.

Oh sorry, my bad - I somehow managed to miss that :/ I'll rerun for the right scenario.

@roji

roji commented May 22, 2021

Copy link
Copy Markdown
Contributor

@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 Unable to locate tests ['aspcore-mw-ef-pg-up'].

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.

@lauxjpn

lauxjpn commented May 23, 2021

Copy link
Copy Markdown
Contributor Author

@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).

@roji

roji commented May 23, 2021

Copy link
Copy Markdown
Contributor

Sure thing - whatever works. Just point me at some commits.

@lauxjpn

lauxjpn commented May 23, 2021

Copy link
Copy Markdown
Contributor Author

@roji

roji commented May 24, 2021

Copy link
Copy Markdown
Contributor

@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.

commit scenario Run 1
cc644ad Before any changes 61,680
028bc47 test/aspnetcore_ef_update_1 62,038
c224b8a test/aspnetcore_ef_update_2 61,914
c3fa2ef test/aspnetcore_ef_update_3 61,678
Before any changes
dotnet run --config Z:\projects\AspNetBenchmarks\scenarios\te.benchmarks.yml --scenario multiple_update_aspnet --profile aspnet-citrine-lin --application.source.repository https://github.com/lauxjpn/FrameworkBenchmarks --application.source.branchOrCommit test/aspnetcore_ef_update_1#cc644ada682b258d88156c9826ef8ce92fc1daff --application.framework net6.0 --variable warmup=45 --variable duration=300

| db                  |         |
| ------------------- | ------- |
| CPU Usage (%)       | 49      |
| Cores usage (%)     | 1,373   |
| Working Set (MB)    | 140     |
| Build Time (ms)     | 1,709   |
| Start Time (ms)     | 363     |
| Published Size (KB) | 914,035 |


| application         |         |
| ------------------- | ------- |
| CPU Usage (%)       | 99      |
| Cores usage (%)     | 2,762   |
| Working Set (MB)    | 462     |
| Build Time (ms)     | 3,403   |
| Start Time (ms)     | 481     |
| Published Size (KB) | 217,432 |


| load                   |            |
| ---------------------- | ---------- |
| CPU Usage (%)          | 4          |
| Cores usage (%)        | 121        |
| Working Set (MB)       | 37         |
| Private Memory (MB)    | 358        |
| Start Time (ms)        | 0          |
| First Request (ms)     | 1,345      |
| Requests/sec           | 61,680     |
| Requests               | 18,509,929 |
| Mean latency (ms)      | 4.17       |
| Max latency (ms)       | 144.55     |
| Bad responses          | 0          |
| Socket errors          | 0          |
| Read throughput (MB/s) | 9.28       |
| Latency 50th (ms)      | 3.99       |
| Latency 75th (ms)      | 4.24       |
| Latency 90th (ms)      | 4.60       |
| Latency 99th (ms)      | 6.67       |
test/aspnetcore_ef_update_1
dotnet run --config Z:\projects\AspNetBenchmarks\scenarios\te.benchmarks.yml --scenario multiple_update_aspnet --profile aspnet-citrine-lin --application.source.repository https://github.com/lauxjpn/FrameworkBenchmarks --application.source.branchOrCommit test/aspnetcore_ef_update_1#028bc47a8b819ac6131fecf52f11e564f9efb0fc --application.framework net6.0 --variable warmup=45 --variable duration=300

| db                  |         |
| ------------------- | ------- |
| CPU Usage (%)       | 51      |
| Cores usage (%)     | 1,417   |
| Working Set (MB)    | 140     |
| Build Time (ms)     | 1,736   |
| Start Time (ms)     | 342     |
| Published Size (KB) | 914,035 |


| application         |         |
| ------------------- | ------- |
| CPU Usage (%)       | 99      |
| Cores usage (%)     | 2,759   |
| Working Set (MB)    | 464     |
| Build Time (ms)     | 15,058  |
| Start Time (ms)     | 486     |
| Published Size (KB) | 217,431 |


| load                   |            |
| ---------------------- | ---------- |
| CPU Usage (%)          | 4          |
| Cores usage (%)        | 124        |
| Working Set (MB)       | 37         |
| Private Memory (MB)    | 358        |
| Start Time (ms)        | 0          |
| First Request (ms)     | 1,325      |
| Requests/sec           | 62,038     |
| Requests               | 18,615,515 |
| Mean latency (ms)      | 4.14       |
| Max latency (ms)       | 63.60      |
| Bad responses          | 0          |
| Socket errors          | 0          |
| Read throughput (MB/s) | 9.33       |
| Latency 50th (ms)      | 3.96       |
| Latency 75th (ms)      | 4.21       |
| Latency 90th (ms)      | 4.56       |
| Latency 99th (ms)      | 7.52       |
test/aspnetcore_ef_update_2
dotnet run --config Z:\projects\AspNetBenchmarks\scenarios\te.benchmarks.yml --scenario multiple_update_aspnet --profile aspnet-citrine-lin --application.source.repository https://github.com/lauxjpn/FrameworkBenchmarks --application.source.branchOrCommit test/aspnetcore_ef_update_1#c224b8aa0c9cfb4ce6196318040e885fb370d9b0 --application.framework net6.0 --variable warmup=45 --variable duration=300

| db                  |         |
| ------------------- | ------- |
| CPU Usage (%)       | 50      |
| Cores usage (%)     | 1,388   |
| Working Set (MB)    | 139     |
| Build Time (ms)     | 1,774   |
| Start Time (ms)     | 343     |
| Published Size (KB) | 914,035 |


| application         |         |
| ------------------- | ------- |
| CPU Usage (%)       | 98      |
| Cores usage (%)     | 2,756   |
| Working Set (MB)    | 468     |
| Build Time (ms)     | 17,159  |
| Start Time (ms)     | 470     |
| Published Size (KB) | 217,432 |


| load                   |            |
| ---------------------- | ---------- |
| CPU Usage (%)          | 4          |
| Cores usage (%)        | 120        |
| Working Set (MB)       | 37         |
| Private Memory (MB)    | 358        |
| Start Time (ms)        | 0          |
| First Request (ms)     | 1,339      |
| Requests/sec           | 61,914     |
| Requests               | 18,580,222 |
| Mean latency (ms)      | 4.15       |
| Max latency (ms)       | 61.81      |
| Bad responses          | 0          |
| Socket errors          | 0          |
| Read throughput (MB/s) | 9.32       |
| Latency 50th (ms)      | 3.98       |
| Latency 75th (ms)      | 4.23       |
| Latency 90th (ms)      | 4.58       |
| Latency 99th (ms)      | 6.68       |
test/aspnetcore_ef_update_3
dotnet run --config Z:\projects\AspNetBenchmarks\scenarios\te.benchmarks.yml --scenario multiple_update_aspnet --profile aspnet-citrine-lin --application.source.repository https://github.com/lauxjpn/FrameworkBenchmarks --application.source.branchOrCommit test/aspnetcore_ef_update_1#c3fa2ef65a4061851f5de3f272a3160b787758f1 --application.framework net6.0 --variable warmup=45 --variable duration=300

| db                  |         |
| ------------------- | ------- |
| CPU Usage (%)       | 49      |
| Cores usage (%)     | 1,383   |
| Working Set (MB)    | 139     |
| Build Time (ms)     | 1,833   |
| Start Time (ms)     | 348     |
| Published Size (KB) | 914,035 |


| application         |         |
| ------------------- | ------- |
| CPU Usage (%)       | 99      |
| Cores usage (%)     | 2,769   |
| Working Set (MB)    | 465     |
| Build Time (ms)     | 15,033  |
| Start Time (ms)     | 474     |
| Published Size (KB) | 217,431 |


| load                   |            |
| ---------------------- | ---------- |
| CPU Usage (%)          | 4          |
| Cores usage (%)        | 121        |
| Working Set (MB)       | 37         |
| Private Memory (MB)    | 358        |
| Start Time (ms)        | 0          |
| First Request (ms)     | 1,328      |
| Requests/sec           | 61,678     |
| Requests               | 18,509,430 |
| Mean latency (ms)      | 4.17       |
| Max latency (ms)       | 56.28      |
| Bad responses          | 0          |
| Socket errors          | 0          |
| Read throughput (MB/s) | 9.28       |
| Latency 50th (ms)      | 4.00       |
| Latency 75th (ms)      | 4.25       |
| Latency 90th (ms)      | 4.60       |
| Latency 99th (ms)      | 6.64       |
ASP.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

@lauxjpn

lauxjpn commented May 25, 2021 •

Copy link
Copy Markdown
Contributor Author

The changes below seem small enough to be generally variance/noise.

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
Method QueryLevels Mean Error StdDev Gen 0 Gen 1 Gen 2 Allocated
Update_3 1 42.10 ns 0.162 ns 0.152 ns 0.0191 - - 120 B
Update_1 1 54.67 ns 0.216 ns 0.202 ns 0.0331 - - 208 B
Baseline 1 169.15 ns 0.569 ns 0.504 ns 0.0777 - - 488 B
Update_2 1 160.19 ns 0.387 ns 0.343 ns 0.0725 - - 456 B
Method QueryLevels Mean Error StdDev Gen 0 Gen 1 Gen 2 Allocated
Update_1 5 190.23 ns 0.531 ns 0.496 ns 0.0484 - - 304 B
Update_2 5 378.29 ns 0.668 ns 0.625 ns 0.0777 - - 488 B
Baseline 5 385.29 ns 1.069 ns 1.000 ns 0.0916 - - 576 B
Update_3 5 467.10 ns 0.932 ns 0.872 ns 0.1106 - - 696 B
Method QueryLevels Mean Error StdDev Gen 0 Gen 1 Gen 2 Allocated
Update_1 10 362.61 ns 0.579 ns 0.542 ns 0.0648 - - 408 B
Update_2 10 710.21 ns 1.522 ns 1.349 ns 0.1307 - - 824 B
Baseline 10 723.73 ns 2.760 ns 2.582 ns 0.1650 - - 1040 B
Update_3 10 1,295.43 ns 0.912 ns 0.853 ns 0.2251 - - 1417 B
Method QueryLevels Mean Error StdDev Gen 0 Gen 1 Gen 2 Allocated
Update_1 15 520.22 ns 0.783 ns 0.654 ns 0.0858 - - 544 B
Update_2 15 995.24 ns 3.339 ns 3.123 ns 0.1373 - - 864 B
Baseline 15 997.09 ns 3.121 ns 2.919 ns 0.1755 - - 1104 B
Update_3 15 2,437.42 ns 3.142 ns 2.786 ns 0.3395 - - 2137 B
Method QueryLevels Mean Error StdDev Gen 0 Gen 1 Gen 2 Allocated
Update_1 20 684.12 ns 1.217 ns 1.139 ns 0.1078 - - 680 B
Update_2 20 1,358.42 ns 3.361 ns 3.144 ns 0.2308 - - 1456 B
Baseline 20 1,362.78 ns 3.293 ns 3.080 ns 0.2880 - - 1808 B
Update_3 20 3,821.48 ns 4.338 ns 3.845 ns 0.4501 - - 2858 B
Program.cs
using 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 summary
// * Summary *

BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19041.985 (2004/?/20H1)
Intel Core i7-9700K CPU 3.60GHz (Coffee Lake), 1 CPU, 8 logical and 8 physical cores
.NET Core SDK=5.0.203
  [Host]     : .NET Core 5.0.6 (CoreCLR 5.0.621.22011, CoreFX 5.0.621.22011), X64 RyuJIT
  DefaultJob : .NET Core 5.0.6 (CoreCLR 5.0.621.22011, CoreFX 5.0.621.22011), X64 RyuJIT


|   Method | QueryLevels |        Mean |    Error |   StdDev |  Gen 0 | Gen 1 | Gen 2 | Allocated |
|--------- |------------ |------------:|---------:|---------:|-------:|------:|------:|----------:|
| Baseline |           1 |   169.15 ns | 0.569 ns | 0.504 ns | 0.0777 |     - |     - |     488 B |
| Update_1 |           1 |    54.67 ns | 0.216 ns | 0.202 ns | 0.0331 |     - |     - |     208 B |
| Update_2 |           1 |   160.19 ns | 0.387 ns | 0.343 ns | 0.0725 |     - |     - |     456 B |
| Update_3 |           1 |    42.10 ns | 0.162 ns | 0.152 ns | 0.0191 |     - |     - |     120 B |
| Baseline |           5 |   385.29 ns | 1.069 ns | 1.000 ns | 0.0916 |     - |     - |     576 B |
| Update_1 |           5 |   190.23 ns | 0.531 ns | 0.496 ns | 0.0484 |     - |     - |     304 B |
| Update_2 |           5 |   378.29 ns | 0.668 ns | 0.625 ns | 0.0777 |     - |     - |     488 B |
| Update_3 |           5 |   467.10 ns | 0.932 ns | 0.872 ns | 0.1106 |     - |     - |     696 B |
| Baseline |          10 |   723.73 ns | 2.760 ns | 2.582 ns | 0.1650 |     - |     - |    1040 B |
| Update_1 |          10 |   362.61 ns | 0.579 ns | 0.542 ns | 0.0648 |     - |     - |     408 B |
| Update_2 |          10 |   710.21 ns | 1.522 ns | 1.349 ns | 0.1307 |     - |     - |     824 B |
| Update_3 |          10 | 1,295.43 ns | 0.912 ns | 0.853 ns | 0.2251 |     - |     - |    1417 B |
| Baseline |          15 |   997.09 ns | 3.121 ns | 2.919 ns | 0.1755 |     - |     - |    1104 B |
| Update_1 |          15 |   520.22 ns | 0.783 ns | 0.654 ns | 0.0858 |     - |     - |     544 B |
| Update_2 |          15 |   995.24 ns | 3.339 ns | 3.123 ns | 0.1373 |     - |     - |     864 B |
| Update_3 |          15 | 2,437.42 ns | 3.142 ns | 2.786 ns | 0.3395 |     - |     - |    2137 B |
| Baseline |          20 | 1,362.78 ns | 3.293 ns | 3.080 ns | 0.2880 |     - |     - |    1808 B |
| Update_1 |          20 |   684.12 ns | 1.217 ns | 1.139 ns | 0.1078 |     - |     - |     680 B |
| Update_2 |          20 | 1,358.42 ns | 3.361 ns | 3.144 ns | 0.2308 |     - |     - |    1456 B |
| Update_3 |          20 | 3,821.48 ns | 4.338 ns | 3.845 ns | 0.4501 |     - |     - |    2858 B |

// * Hints *
Outliers
  Benchmarks.Baseline: Default -> 1 outlier  was  removed (172.12 ns)
  Benchmarks.Update_2: Default -> 1 outlier  was  removed (162.81 ns)
  Benchmarks.Update_2: Default -> 1 outlier  was  removed, 3 outliers were detected (709.23 ns, 709.37 ns, 718.23 ns)
  Benchmarks.Update_1: Default -> 2 outliers were removed, 4 outliers were detected (520.37 ns, 520.47 ns, 523.38 ns, 525.71 ns)
  Benchmarks.Update_3: Default -> 1 outlier  was  removed (2.45 us)
  Benchmarks.Update_3: Default -> 1 outlier  was  removed (3.84 us)

// * Legends *
  QueryLevels : Value of the 'QueryLevels' parameter
  Mean        : Arithmetic mean of all measurements
  Error       : Half of 99.9% confidence interval
  StdDev      : Standard deviation of all measurements
  Gen 0       : GC Generation 0 collects per 1000 operations
  Gen 1       : GC Generation 1 collects per 1000 operations
  Gen 2       : GC Generation 2 collects per 1000 operations
  Allocated   : Allocated memory per single operation (managed only, inclusive, 1KB = 1024B)
  1 ns        : 1 Nanosecond (0.000000001 sec)

// * Diagnostic Output - MemoryDiagnoser *


// ***** BenchmarkRunner: End *****
// ** Remained 0 benchmark(s) to run **
Run time: 00:06:20 (380.61 sec), executed benchmarks: 20

Global total time: 00:06:23 (383.72 sec), executed benchmarks: 20
// * Artifacts cleanup *

The Update_1 benchmark (this PR) performs about twice as well as the Baseline benchmark, and is overall the fastest implementation with the smallest memory footprint, with the expected exception of the 1-query-case, where no deduplication code would be necessary in the first place.

Also, for the Update_1 benchmark in relation to others, even multiple standard deviations don't overlap with each other, so I think this PR is good as it, unless we want to add a code branch to skip deduplication entirely for the 1-query-case.

@roji

roji commented May 25, 2021

Copy link
Copy Markdown
Contributor

Yes, the gain is small in comparison to disk write operations, so its difficult to measure accurately without running these benchmarks many times.

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!

@NateBrady23
NateBrady23 merged commit ed959a6 into TechEmpower:master May 25, 2021
@lauxjpn
lauxjpn deleted the fix/aspnetcore_ef_update branch May 25, 2021 15:19
@n-stefan

n-stefan commented Jun 5, 2021

Copy link
Copy Markdown
Contributor

This benchmark isn't run currently, is it?

@lauxjpn

lauxjpn commented Jun 5, 2021

Copy link
Copy Markdown
Contributor Author

For Npgsql, it is not since #6568 (comment).
For MySqlConnector, it will be run once #6565 is merged.

@n-stefan

n-stefan commented Jun 5, 2021

Copy link
Copy Markdown
Contributor

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants