System.Linq.Parallel is missing optimizations for IReadOnlyList<T> and IReadOnlyCollection<T>
Description
PartitionedDataSource.InitializePartitions only checks for IList<T> here: https://github.com/dotnet/runtime/blob/732f597ad3b75f1384eefa10cf5484ce3b221087/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Partitioning/PartitionedDataSource.cs#L85-L146
ScanQueryOperator has paths specifically for IList<T> but not IReadOnlyList<T> here https://github.com/dotnet/runtime/blob/732f597ad3b75f1384eefa10cf5484ce3b221087/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/ScanQueryOperator.cs#L61 and here https://github.com/dotnet/runtime/blob/732f597ad3b75f1384eefa10cf5484ce3b221087/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/ScanQueryOperator.cs#L100
ParallelEnumerable.Count only uses the count from ICollection<T> and not IReadOnlyCollection<T> here https://github.com/dotnet/runtime/blob/732f597ad3b75f1384eefa10cf5484ce3b221087/src/libraries/System.Linq.Parallel/src/System/Linq/ParallelEnumerable.cs#L1855 and here https://github.com/dotnet/runtime/blob/732f597ad3b75f1384eefa10cf5484ce3b221087/src/libraries/System.Linq.Parallel/src/System/Linq/ParallelEnumerable.cs#L1926
This looks like some holdover from the pre-netfx4.5 days. Consumers really shouldn't have to implement IList<T> with all the modifying members throwing exceptions for every read-only collection just to get better performance from PLINQ.
This should be covered under #42254.
Tagging subscribers to this area: @dotnet/area-system-linq-parallel See info in area-owners.md if you want to be subscribed.
This should be covered under #42254.
Urgh what a mess 😆
That issue seems to begin with to be primarily about IReadOnlyCollection, but then some of the discussion also touches on random-access with IReadOnlyList, so dunno if this belongs fully under that.
I'm interested in working on this issue. I noticed that it was mentioned that #42254 might cover this, but as @poizan42 pointed out, this specific issue in System.Linq.Parallel has already identified the exact locations (like PartitionedDataSource.cs and ScanQueryOperator.cs) where IReadOnlyList
This would need design review, or at least triage to be continued. The work for this issue is trivial, and the important part is agreement.
This would need design review, or at least triage to be continued. The work for this issue is trivial, and the important part is agreement.
In my opinion the core issue isn't just performance, it’s that PLINQ currently incentivizes using mutable interfaces. Since modern .NET best practices push for immutability (e.g., IReadOnlyList
Currently we are essentially penalizing developers for following thread-safety best practices by forcing them onto the slower Chunk Partitioning path. This inconsistency in the PLINQ API surface is a strong reason to address this fix independently of the broader runtime discussions
To support the case for addressing this, I've conducted a benchmark to quantify the current performance penalty.
When using a custom IReadOnlyList<int> (which bypasses the current List<int>-only optimization), PLINQ is forced into Chunk Partitioning, leading to significant overhead:
| Method | Mean | Ratio | Allocated |
|---|---|---|---|
List<int>.AsParallel() |
14.07 ms | 1.00 | 3.74 KB |
IReadOnlyList<int>.AsParallel() |
42.47 ms | 3.02 | 6.42 KB |
These results (from a 10M element dataset) show a 3x slowdown and a 72% increase in allocations.
Click to see the Benchmark code used
[MemoryDiagnoser]
public class PLINQBenchmark
{
private List<int> _list;
private FakeReadOnlyList _customReadOnly;
[GlobalSetup]
public void Setup()
{
_list = Enumerable.Range(0, 10_000_000).ToList();
_customReadOnly = new FakeReadOnlyList(_list);
}
[Benchmark(Baseline = true)]
public long ListParallel() => _list.AsParallel().Sum(x => (long)x);
[Benchmark]
public long CustomReadOnlyParallel() => _customReadOnly.AsParallel().Sum(x => (long)x);
private class FakeReadOnlyList : IReadOnlyList<int>
{
private readonly List<int> _inner;
public FakeReadOnlyList(List<int> inner) => _inner = inner;
public int this[int index] => _inner[index];
public int Count => _inner.Count;
public IEnumerator<int> GetEnumerator() => _inner.GetEnumerator();
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
}
}
While the code change itself might be trivial, this benchmark proves that we are currently leaving a lot of performance on the table for developers who adhere to immutability best practices. I believe this provides a strong justification for a triage/review to unblock this fix.
I agree that a design review is necessary, but I'd like to highlight a practical point. Issue #42254 has been open for years because it tackles a broader architectural change.
However, as noted by @EgorBo and @VSadov in that thread, the performance concerns regarding covariant interface dispatch (which previously hindered these optimizations) have been largely mitigated since .NET 5.0.
While we wait for a "perfect" global fix, developers on .NET 10 are currently facing a 3x performance penalty in PLINQ when using modern, recommended immutable types. Given that the technical blockers are gone, I believe providing this targeted optimization now is a pragmatic win. It unblocks performance for the community immediately without interfering with long-term goals. Should we really leave this 300% overhead on the table for another release cycle?
Since modern .NET best practices push for immutability (e.g., IReadOnlyList, ImmutableArray), PLINQ should at the very least offer the same 'Fast Path' for these thread-safe types as it does for mutable ones
All the built-in immutable collections are implementing the mutable collection interfaces, because of the historical implementations taking mutable interfaces.
While the code change itself might be trivial, this benchmark proves that we are currently leaving a lot of performance on the table for developers who adhere to immutability best practices. I believe this provides a strong justification for a triage/review to unblock this fix.
developers on .NET 10 are currently facing a 3x performance penalty in PLINQ when using modern, recommended immutable types.
Custom interfaces are not recommended over the framework built-in ones. Framework built-in types are well adjusted for the performance characteristics and quirks.
it’s that PLINQ currently incentivizes using mutable interfaces
IReadOnly* interfaces are not immutable. It simply means "this particular view is not writeable". The trivial example being:
List<int> x = new List<int>();
IReadOnlyList<int> y = x;
Console.WriteLine(y.Count);
x.Add(5);
Console.WriteLine(y.Count);
.NET in general had historically only provided the singular interfaces and expected you to check collection.IsReadOnly to determine if you could perform additions or removal of elements.
Correspondingly, any collection type should be implementing "both sets" of APIs anyways and this should largely be a non-issue. Updating the various APIs to also check if (typeof(T) is IReadOnly...) then adds unnecessary expense and overhead which only benefits a niche few types while hurting the perf for the majority of other inputs, which is why none of the paths are really doing this today.
If we are eventually able to make the breaking change and have I* and friends implement the IReadOnly* interfaces, then we can update all the paths to just check those paths without incurring said additional overhead. But it is a complex breaking change and has been kicked back several times now, so it's unlikely to happen and users should still be doing the recommended and historical thing anyways (i.e. implement the v2.0 interfaces and say bool IsReadOnly => true