runtime: List Add is way slower (almost 3 times) in `net9.0 preview 3` than with `net8.0`
With the latest preview 3 (net9) there seems to be a major performance regression on MacOS 14.4 (M2 Pro) with lists. Given that they are one of the most used types, it should receive special treatment.
Benchmark
[Benchmark]
public List<int> ListAdd10000()
{
var list = new List<int>();
for (var i = 0; i < 10_000; i++)
{
list.Add(i);
}
return list;
}
[Benchmark]
public List<int> ListAdd10000PreAlloc()
{
var list = new List<int>(10_000);
for (var i = 0; i < 10_000; i++)
{
list.Add(i);
}
return list;
}
Results:
BenchmarkDotNet v0.13.12, macOS Sonoma 14.4.1 (23E224) [Darwin 23.4.0]
Apple M2 Pro, 1 CPU, 12 logical and 12 physical cores
.NET SDK 9.0.100-preview.3.24204.13
[Host] : .NET 9.0.0 (9.0.24.17209), Arm64 RyuJIT AdvSIMD
.NET 8.0 : .NET 8.0.2 (8.0.224.6711), Arm64 RyuJIT AdvSIMD
.NET 9.0 : .NET 9.0.0 (9.0.24.17209), Arm64 RyuJIT AdvSIMD
| Method | Runtime | Mean | Error | StdDev | Ratio |
|--------------------- |--------- |----------:|----------:|----------:|------:|-
| ListAdd10000 | .NET 8.0 | 9.739 us | 0.0236 us | 0.0209 us | 1.00 |
| ListAdd10000 | .NET 9.0 | 25.646 us | 0.1531 us | 0.1432 us | 2.63 |
| | | | | | |
| ListAdd10000PreAlloc | .NET 8.0 | 6.701 us | 0.0175 us | 0.0146 us | 1.00 |
| ListAdd10000PreAlloc | .NET 9.0 | 22.562 us | 0.1429 us | 0.1336 us | 3.37 |
Interestingly even the pre-allocated list is comparably slow.
dotnet --info
Output
dotnet --info .NET SDK: Version: 9.0.100-preview.3.24204.13 Commit: 81f61d8290 Workload version: 9.0.100-manifests.77bb7ba9 MSBuild version: 17.11.0-preview-24178-16+7ca3c98faRuntime Environment: OS Name: Mac OS X OS Version: 14.4 OS Platform: Darwin RID: osx-arm64 Base Path: /usr/local/share/dotnet/sdk/9.0.100-preview.3.24204.13/
.NET workloads installed: There are no installed workloads to display.
Host: Version: 9.0.0-preview.3.24172.9 Architecture: arm64 Commit: 9e6ba1f68c
.NET SDKs installed: 6.0.417 [/usr/local/share/dotnet/sdk] 7.0.306 [/usr/local/share/dotnet/sdk] 7.0.404 [/usr/local/share/dotnet/sdk] 8.0.100 [/usr/local/share/dotnet/sdk] 8.0.101 [/usr/local/share/dotnet/sdk] 8.0.200 [/usr/local/share/dotnet/sdk] 9.0.100-preview.2.24121.2 [/usr/local/share/dotnet/sdk] 9.0.100-preview.2.24157.14 [/usr/local/share/dotnet/sdk] 9.0.100-preview.3.24204.13 [/usr/local/share/dotnet/sdk]
.NET runtimes installed: Microsoft.AspNetCore.App 6.0.25 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 7.0.14 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 8.0.0 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 8.0.1 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 8.0.2 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 9.0.0-preview.2.24120.6 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 9.0.0-preview.2.24128.4 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 9.0.0-preview.3.24172.13 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App] Microsoft.NETCore.App 6.0.25 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App] Microsoft.NETCore.App 7.0.14 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App] Microsoft.NETCore.App 8.0.0 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App] Microsoft.NETCore.App 8.0.1 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App] Microsoft.NETCore.App 8.0.2 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App] Microsoft.NETCore.App 9.0.0-preview.2.24120.11 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App] Microsoft.NETCore.App 9.0.0-preview.2.24128.5 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App] Microsoft.NETCore.App 9.0.0-preview.3.24172.9 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App]
Other architectures found: x64 [/usr/local/share/dotnet/x64]
Environment variables: Not set
global.json file: Not found
Learn more: https://aka.ms/dotnet/info
Download .NET: https://aka.ms/dotnet/download
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Reactions: 28
- Comments: 50 (38 by maintainers)
Commits related to this issue
- JIT: Check for potential store-to-load forwarding before reordering ldr -> ldp Very targeted fix for #93401 and #101437: before reordering two indirections, check if there is a potential store in the... — committed to jakobbotsch/runtime by jakobbotsch 2 years ago
- JIT: Check for potential store-to-load forwarding before reordering ldr -> ldp (#105695) Very targeted fix for #93401 and #101437: before reordering two indirections, check if there is a potential s... — committed to SteveDunn/runtime by jakobbotsch 2 years ago
The fun part that this benchmark is 3x faster under x64 emulation (Rosetta), e.g.:
Then:
Native (arm64):
Rosetta (x64) on the same hw
Reminder that Linux on Apple Silicon is a thing, both virtualized and bare metal, and virtual Windows ARM64 on Apple Silicon is also a thing. Please do not gate this on macOS only.
Given the LSE2 theory, I think it makes sense to treat this as a performance issue potentially affecting more CPU platforms (especially future ones), given that there is a plausible explanation for the mechanism and why the code is, for at least some logical implementations, actually sub-optimal. If the gains of this peephole opt are otherwise minimal, and it’s not easy to detect the problem code sequences (the ones where it triggers extra stalls) then I think the logical thing to do is just disable it across the board. Alternatively, if you think this is rare enough and the List.Add case is an outlier, then just work around it there (e.g. with the
versionchange).But please don’t use OS platform as a gate for this, since that makes no sense given multiple OSes exist (you’d have to use CPU implementer instead, and I assume that’s not practical given ahead-of-time compilation?).
I’ve just checked it locally - I’ve built a runtime that exactly matches 9.0-preview3 and removed the Ldr->Ldp optimization - it has fixed the perf 😐
We are reviewing this issue thanks for raising it!
My guess, given the above, is then that since
LSE2makesldpatomic for loads that exist within a 16-byte window (and we know these will be since the they’ll be 8-byte aligned), that the write to_versionis placing a stall against the read for_size, which wouldn’t exist for two independentldr.The use of LDP instructions is generally encouraged. In this specific case, the structure of the loop (that includes a memory dependence between stores and loads), coupled with the use of LDP instructions prevents certain hardware optimizations from engaging. The small and tight nature of the loop also exacerbates the impact.
Please also see section 4.6.11 of the Apple Silicon CPU optimization guide.
So we have a good guess (discussed internally) what’s going on here, but it’s not clear how to detect bad patterns and disable ldr->ldp optimization. The PRs which added
ldr->ldpoptimization only have a very few improvement reports attached to them (except ldp for SIMD regs), so we can, probably, just conservatively disable it for Apple platforms (we’ve confirmed that this problem is Apple specific at this point).I think the first thing we have to do is to add macOS-arm64 platform to our dotnet/performance runs (it’s currently Linux and Windows only) before we make any changes.
Perhaps this could also serve as a tipping point to finally remove the version checks from
List<T>altogether (or leave them in debug only)? 😄Yes, for some scenarios. For most cases
ldpwill be strictly better/more efficient, but for others it has the chance to introduce a new data dependency due to the LSE2 requirement that it be atomic in some scenarios.If you have (semi pseudo-code):
Then the code will first iterate through the loop normally, and the second iteration
ldr w0, [addr1]will be scheduled but will be dependent onstr [addr1], w0from the previous iteration completing first. However,ldr w1, [addr2]is a separate load and therefore can happen independently of the first load and so we can continue onto executingdo something with w1even if thestr [addr1], w0hasn’t completed yet.This all follows the documented Arm64 memory model, which is a weakly ordered model. Where by default:
and where the important part of the general semantics under B2.3 Definition of the Arm memory model can basically be summarized as a read effect
E2will occur after write effectE1if they are to the same location and cannot be reordered with regards to eachother (it is formally defined as theLocal read successor).Thus, given the above the follow program is strictly equivalent:
LSE2, however, changes the semantics for
ldpsuch thatThis change to make the load a single-copy atomic that encompasses both registers, rather than it being 2 separate single-copy atomic operations (one for each register), really flips how
ldpworks (at least based on my understanding of the rules) and it means that due to the memory ordering rules of read effects to write effects and forlocal read successors, that the load of data intow1can no longer happen independently of thestr [addr], w0a dummy field between _size and _version in
List<>fixes the issue as well (since it breaks the ldp optimization too)Doesn’t repro on Linux-arm64
There are different classifications of errors/exceptions, ranging from “the application messed up” to “the system messed up”. While code ideally tries to order things such that you avoid the potential for torn state, you can not always perform updates atomically and may not be able to ensure all exceptions are done in a way that avoids the ability to have torn state. Accordingly, it is not safe to make the assumption that all exceptions are safe to catch. It is not safe to assume how a given piece of external to the module code does its operations and whether or not it could safely handle torn state.
Most code is a best effort and cannot necessarily capture all possible nuance. This is accordingly why C++ explicitly documents behavior as undefined or implementation defined in many cases. It is why the C++ spec explicitly defines
valid but unspecified stateearly and refers to it regularly. Such a definition is important as it is very different from something which is in a fully unspecified state and therefore may be invalid.To quote a part of the spec directly,
insert, as it appears forstd::vector<T>in26.3.11.5 vector modifiers, explicitly documents that there are cases where there must be no effects, but that there is potential for there to be effects in other scenarios as it is impossible to definitively assert that it can be safe:Given the above, there are many more cases of potential torn state for inserting into a
std::vectorthen there are for aList<T>which namely comes about from the existence ofcopy/move constructorsandassignment operatorsupport. Since .NET doesn’t itself have those concerns for arbitraryT, and sinceAddfunctions asinserting a single element at the end, there are no effects other than anOOMthat can occur in single-threaded code and thus no potential for torn state.OOM, as thrown by the GC, is explicitly documented as acatastrophic exception. The docs further cover that if you were to catch the exception, you are really expected to do the bare minimal handling and thenfail fast. Much like other types ofcatastrophic exception(such asStackOverflow), it is not expected to be something an application can reasonably recover from nor is something that you may guaranteed to be able to catch and handle.This documentation is what makes when
_versionis updated forAdd, not really matter. One could argue its better for it to happen later since its done after the necessary mutations have been made. One could alternatively argue its better for it to happen sooner, as it may help expose multithreaded access issues sooner. But neither is more or less correct, what happens is undefined behavior for any scenario where it might be an issue.It is important to note that there are other types of “system thrown exceptions” which are representative of catastrophic failures, such as
ExecutionEngineExceptionorStackOverflowException. There are also exception types (such asOverflowException,IndexOutOfRangeException, andNullReferenceException) which are not catastrophic but are thrown by the system as an implicit side effect an operation. These all fall into the same general bucket, which is to say they are often representative that it may be unsafe to assume the state of the object is “valid”.We then have the more typical application thrown exceptions, such as
ArgumentException, where it is only ever explicitly thrown by the developer. It is extremely typical for this type of exception to happen up front before any kinds of state mutations have happened and so its often considered okay to presume the state remains “valid, but unspecified” when one is thrown.There is, of course, code out there that violates these presumptions. There is code that will manually throw system exceptions themselves (despite analyzers existing telling users to not do that) and there is code that will throw application exceptions after state mutations have occurred. In many cases this may be unintentional and could be caused by a myriad of different considerations, such as behavioral or breaking changes made by a dependency. However, it just reiterates that all of this remains a “best effort”, that exceptions in general are meant to be exceptional, and that one needs to be considerate when catching or otherwise handling exceptions.
Minimal repro:
Codegen diff for
Test(): https://www.diffchecker.com/72No1VJ6/ Left - Main, ~191 ms per iteration Right - LDP optimization disabled, ~67 ms per iteration (~3x faster)I like that guess. Although, the fact that on Graviton 3 we’re seeing 23 us for both cases (and I am seeing similar numbers on Ampere-linux-arm64) while x64 and apple m1 show 7us for the best case, might be hinting something else
Wouldn’t that only solve the problem for List? Leaving an area for potential other regressions now and the future!?
I think @EgorBo hit the nail on the head with moving the increment of
_versionlast in theAddmethod.Not only does it (seemingly) avoid the CPU stall, I’d argue it’s also correct. Having the increment at the top means it always increments version, even if something later goes wrong, such as terminating with an OOM exception. Now you have placed the list in a conceptually inconsistent state; the List is not modified, but
_versionclaims it is modified. Placing the increment last makes sure it’s only incremented once everything else is completed.Performace-wise, having that read-modify-write just before method return could allow the CPU decode/execute the return (even if it may be only be a conceptual return instruction, due to the
AggressiveInliningtag) in parallel with the RMW (assuming superscalar CPU).Provided that logic is valid, perhaps it could be worth running comparative perf-tests for every ISA supported, with the RMW at head, vs. moved to the very end?
The core issue with the JIT obviously remains, but it would at least fix a logic error in the runtime.
It could potentially be related to behavioral changes that exist for
LDPwhenLSE2is supported.In particular
The actual operation (or a snippet of it) is then described loosely as:
So it may be beneficial to test this on a Linux machine with LSE2 to see if that makes a difference or not.
Minimal repro for the Apple issue using Clang and inline asm: https://gist.github.com/EgorBo/88196a218559ec93a197a7d1d5600548
ldpmakes this “benchmark” ~4-5x slower. An interesting thing is that if we haveldpandstp- it’s still slow (we thought that the problem reproduces only when we mixstrwithldpandstpwithldpwould be fine)Don’t get me wrong - one can still lead this discussion but I do feel it should be handled separately (and not only because of performance characteristics)
Nonsense. If you are dealing with “remote” resources (remote from the CPU’s POV), e.g. graphics cards, network connections, USB devices et.c. it can be valid, but not for local memory, and certainly not for collection classes. This problem was solved decades ago in C++ std library.
Again, nonsense. This is a simple matter of order of mutation. You simply do not modify the object until you have performed all potentially-exception-throwing operations, collecting their results in local variable(s). Once that is done, you can mutate
thisobject fields in whatever order you like.I didn’t mention multi-threading, since the current design breaks even single-threaded.
Here you expect the iterator to still be valid, and the collection object to be unmodified. With current implementation it is not. With the proposed change it is.
I hope the vast majority of people would prefer at least the basic level of exception-safe code in the core library.
Since that’s so silly, I expected to find a smiley at the end. Lacking that, I have to assume it’s a serious question. No, obviously not.
_versionis a monotonic counter, intended to keep count of number-of-internal-state-modifications to the object. Let us try an analogy:At this time, disregarding potential transaction fees, interest and so on, you expect X == Y. However, what’s the bank internal transaction counter for your account (the equivalent of
List._version)? Would you excpt that to roll back on the withdrawal? No, of course not. Heck, it’s probably illegal in most civilized nations to do such a rollback.My expectation remains that this is due to LSE2 making
ldpatomic if it doesn’t split a 16-byte window and that’s causing the write to stall the otherwise unrelated read.I expect that if someone has an LSE2 capable Linux box, they’d see the same perf hit. The hard problem is that not many easily testable A64 CPUs have LSE2 currently outside Apple M1 and later.
Graviton 3:
To @tannergooding’s point though, either the hardware or the kernel I am using do not support LSE2 based on dmesg output.
I’d suggest people open API suggestions for cases like this:
The general API review process is detailed here: https://github.com/dotnet/runtime/blob/main/docs/project/api-review-process.md
The template for a new API proposal is then: https://github.com/dotnet/runtime/issues/new?assignees=&labels=api-suggestion&projects=&template=02_api_proposal.yml&title=[API+Proposal]%3A+
It really doesn’t need to be that complex and can really just detail that something like
Process.TryGetProcessByIdwould be beneficial because the current version throwsArgumentExceptionif theiddoesn’t exist and there is no safe way to deterministically know if a process id remains valid since a separate process is strictly running concurrently and could shut down in between some check and query.There’s notably, beyond the LSE2 changes, a number of additional changes to the memory model specifically for Armv8.4+ (detailed in
B2.2.1.1 Changes to single-copy atomicity in Armv8.4), including in how coherence works for some types of overlapping reads/writes that are single-copy atomic.Are you saying that LSE2 makes it impossible for the hardware to implement
ldpas efficiently as before, leading to this 3.5x slowdown simply from updating to LSE2 capable ARM64 hardware? It feels hard to believe. I’m hopeful this is some poorly handled case in Apple Silicon that we’ll be able to understand better. Regardless it seems we’ll need to figure out how exactly we want to disable this peephole.Didn’t we change Arm64 to start using the newer Arm64 barrier intstructions for the GC if they existed around that point?
IIRC, @kunalspathak did some of that work.
Doesn’t repro for me on x64-windows:
don’t have an macos-arm64 machine to test