Skip to content

Get rid of static constructor in Task<T> - #93079

Closed
lambdageek wants to merge 3 commits into
dotnet:mainfrom
lambdageek:task-tresult-no-cctor
Closed

lambdageek wants to merge 3 commits into
dotnet:mainfrom
lambdageek:task-tresult-no-cctor

Conversation

@lambdageek

@lambdageek lambdageek commented Oct 5, 2023 •

Copy link
Copy Markdown
Member

Because the default(TResult) task was cached in in the Task<TResult> class, every instantiation would run the static constructor.

With this change, the cached value is stored in
TaskCache.CachedDefaultTask<TResult> instead, and Task<TResult> no longer needs to execute a static constructor.

This is expected to improve startup time for applications that do a lot of async work. (But no measurements have been done). Validated that Task`1::.cctor does not exist in the IL after this change

Because the `default(TResult)` task was cached in in the
`Task<TResult>` class, every instantiation would run the static
constructor.

With this change, the cached value is stored in
`TaskCache.CachedDefaultValueTask<TResult>` instead, and
`Task<TResult>` no longer needs to execute a static constructor.

This is expected to improve startup time for applications that do a
lot of async work.  (But no measurements have been done)
@ghost

ghost commented Oct 5, 2023

Copy link
Copy Markdown

Tagging subscribers to this area: @dotnet/area-system-threading-tasks
See info in area-owners.md if you want to be subscribed.

Issue Details

Because the default(TResult) task was cached in in the Task<TResult> class, every instantiation would run the static constructor.

With this change, the cached value is stored in
TaskCache.CachedDefaultValueTask<TResult> instead, and Task<TResult> no longer needs to execute a static constructor.

This is expected to improve startup time for applications that do a lot of async work. (But no measurements have been done). Validated that ``Task1::.cctor does not exist in the IL after this change

Author: lambdageek
Assignees: -
Labels:

area-System.Threading.Tasks

Milestone: -

@lambdageek

Copy link
Copy Markdown
Member Author

@stephentoub I was looking at logs of the methods that Mono AOT was loading for a ios app and noticed that Task<XYZ>::.cctor was appearing frequently during startup and felt motivated to make it go away. I haven't tried measuring the impact yet, but I kind of want to explore this. Do you think that, in principle, this is beneficial?

/// <summary>
/// A cached task for default(TResult).
/// </summary>
internal static class CachedDefaultValueTask<TResult>

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this introduce any perf issues, in particular for reference type TResults, where it's now slower due to one generic context calling into a different generic context?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@stephentoub There is no such situation in the existing code, as far as I can tell.

The old Task<TResult>.s_DefaultResultTask was only used in 3 places:

  1. in Stream.cs we had Task<int>.s_DefaultResultTask which is a concerete instantiation
  2. in Task.cs we had two uses in Task.FromResult<TResult>(TResult result):
  • if (result is null) return Task<TResult>.s_DefaultResultTask was already a generic context calling into a different generic context. Same as the new code TaskCache.CachedDefaultTask<TResult>.s_DefaultResultTask
  • if (/* result is the same size as one of several primitive value types and the bitpattern matches the default value of that primitive value type */) return Task<TResult>.s_DefaultResultTask; - again this is already one generic context calling into another generic context, although they're not reference types.

I'll try a microbenchmark on Task.FromResult<T>(default(T)) for some different types.

@lambdageek lambdageek Oct 5, 2023 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a microbenchmark:

[GenericTypeArguments(typeof(byte))]
[GenericTypeArguments(typeof(int))]
[GenericTypeArguments(typeof(string))]
[GenericTypeArguments(typeof(Type))]
[BenchmarkCategory(Categories.Libraries)]
public class Perf_FromResult<T>
{
    [Benchmark]
    public void FromResultDefault()
    {
        Task<T> d = Task.FromResult<T>(default(T));
    }
}

Below "runtime-bugs" is baseline, and "runtime" is the PR. Runs were on an macOS arm64 for a release build of coreclr from 70cf9cd

Results for string:

Method Job Toolchain Mean Error StdDev Median Min Max Ratio MannWhitney(5%) RatioSD Allocated Alloc Ratio
FromResultDefault Job-KNJPPY /runtime-bugs/artifacts/bin/testhost/net9.0-osx-Release-arm64/shared/Microsoft.NETCore.App/9.0.0/corerun 6.648 ns 0.1802 ns 0.2075 ns 6.568 ns 6.466 ns 7.146 ns 1.00 Base 0.00 - NA
FromResultDefault Job-SJEICH /runtime/artifacts/bin/testhost/net9.0-osx-Release-arm64/shared/Microsoft.NETCore.App/9.0.0/corerun 6.358 ns 0.0123 ns 0.0109 ns 6.356 ns 6.344 ns 6.379 ns 0.96 Same 0.03 - NA

results for System.Type:

Method Job Toolchain Mean Error StdDev Median Min Max Ratio MannWhitney(5%) Allocated Alloc Ratio
FromResultDefault Job-KNJPPY /runtime-bugs/artifacts/bin/testhost/net9.0-osx-Release-arm64/shared/Microsoft.NETCore.App/9.0.0/corerun 6.391 ns 0.0072 ns 0.0067 ns 6.390 ns 6.384 ns 6.405 ns 1.00 Base - NA
FromResultDefault Job-SJEICH /runtime/artifacts/bin/testhost/net9.0-osx-Release-arm64/shared/Microsoft.NETCore.App/9.0.0/corerun 6.368 ns 0.0136 ns 0.0113 ns 6.365 ns 6.354 ns 6.398 ns 1.00 Same - NA

@stephentoub

Copy link
Copy Markdown
Member

I haven't tried measuring the impact yet, but I kind of want to explore this. Do you think that, in principle, this is beneficial?

Allowing things that should be lazy to indeed be lazy is in general goodness. But I don't have an intuitive sense for whether this will actually move any needles. If it does and it doesn't degrade accesses to this field, I'm fine with it.

[DebuggerDisplay("Id = {Id}, Status = {Status}, Method = {DebuggerDisplayMethodDescription}, Result = {DebuggerDisplayResultDescription}")]
public class Task<TResult> : Task
{
/// <summary>A cached task for default(TResult).</summary>

@jkotas jkotas Oct 5, 2023 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This generates before-field-init constructor. The constructor should be running lazily only when the field is accessed. I do not see how this helps.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this working around Mono running before-field-init constructors earlier than required? It would be better to fix that in Mono for all before-field-init constructors.

@lambdageek lambdageek Oct 5, 2023 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This generates before-field-init constructor. The constructor should be running lazily only when the field is accessed. I do not see how this helps.

It's making the AOT compiler compile a cctor for every instance of Task<T>, even if it is never used

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this working around Mono running before-field-init constructors earlier than required? It would be better to fix that in Mono for all before-field-init constructors.

That is a good point, after we make that fix, this won't show up in startup traces anymore.

I still feel this might be a trimming/AOT win. But I guess it depends on how prevalent Task.FromResult is at different instantiations.

I'll close this tomorrow if I don't see an AOT impact

@jkotas

jkotas commented Oct 5, 2023 •

Copy link
Copy Markdown
Member

I haven't tried measuring the impact yet,

I expect that it is going to regress static footprint of apps that use async heavily (on CoreCLR/NativeAOT at least).

@lambdageek

Copy link
Copy Markdown
Member Author

I haven't tried measuring the impact yet,

I expect that it is going to regress static footprint of apps that use async heavily (on CoreCLR/NativeAOT at least).

I expect the exact opposite. I'll look at aot size tomorrow

@lambdageek

Copy link
Copy Markdown
Member Author

@jkotas Here's the final binaries for the aspnet/Benchmarks "TodosApi" with .NET 8 RC1, a .NET 9 baseline and this PR published with NativeAot in release mode. (I verified that the Ilc .rsp file points to the CoreLib from the relevant build of the runtime):

-rwxr-xr-x  1 alklig  staff  24772904 Oct  6 12:24 TodosApi-net8.0-rc1
-rwxr-xr-x  1 alklig  staff  25103592 Oct  6 12:32 TodosApi-net9.0-PR
-rwxr-xr-x  1 alklig  staff  25103608 Oct  6 12:31 TodosApi-net9.0-baseline

This PR is a couple of bytes smaller.

My intuition is that Task.FromResult<T> is pretty rare in user code - which would mostly use async/await and it is pretty rare in libraries and frameworks - which are more likely to use a TaskCompletionSource<T>

@jkotas

jkotas commented Oct 6, 2023

Copy link
Copy Markdown
Member

It is interesting that the AOT size is same for your test. 16 bytes is not meaningful difference. I think your intuition about Task.FromResult` being used rarely in the core libraries is right. However, it seems to be used often enough to make this change a wash.

@lambdageek lambdageek closed this Oct 6, 2023
@ghost ghost locked as resolved and limited conversation to collaborators Nov 5, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants