KEMBAR78
Return s_defaultResultTask from Task.FromResult in more cases by stephentoub · Pull Request #76349 · dotnet/runtime · GitHub
Skip to content

Conversation

stephentoub
Copy link
Member

Today we return a cached task from Task.FromResult when the TResult is a primitive and its value is 0. But it needn't be constrained to only being a primitive; what matters is that we need to be able to efficiently compare its bit pattern to 0. And we can do that easily now by using Unsafe.SizeOf to check if the size is the same as a primitive, Unsafe casting to that primitive, and then comparing against 0.

[Benchmark]
public async Task<TimeSpan> Cached() => TimeSpan.Zero;
Method Toolchain Mean Ratio Allocated Alloc Ratio
Cached \main\corerun.exe 19.54 ns 1.00 72 B 1.00
Cached \pr\corerun.exe 12.47 ns 0.64 - 0.00

@ghost ghost assigned stephentoub Sep 29, 2022
@stephentoub stephentoub added this to the 8.0.0 milestone Sep 29, 2022
@ghost
Copy link

ghost commented Sep 29, 2022

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

Issue Details

Today we return a cached task from Task.FromResult when the TResult is a primitive and its value is 0. But it needn't be constrained to only being a primitive; what matters is that we need to be able to efficiently compare its bit pattern to 0. And we can do that easily now by using Unsafe.SizeOf to check if the size is the same as a primitive, Unsafe casting to that primitive, and then comparing against 0.

[Benchmark]
public async Task<TimeSpan> Cached() => TimeSpan.Zero;
Method Toolchain Mean Ratio Allocated Alloc Ratio
Cached \main\corerun.exe 19.54 ns 1.00 72 B 1.00
Cached \pr\corerun.exe 12.47 ns 0.64 - 0.00
Author: stephentoub
Assignees: stephentoub
Labels:

area-System.Threading.Tasks

Milestone: -

@stephentoub stephentoub added the tenet-performance Performance related issue label Sep 29, 2022
Today we return a cached task from Task.FromResult when the TResult is a primitive and its value is 0.  But it needn't be constrained to only being a primitive; what matters is that we need to be able to efficiently compare its bit pattern to 0.  And we can do that easily now by using Unsafe.SizeOf to check if the size is the same as a primitive, Unsafe casting to that primitive, and then comparing against 0.
@stephentoub stephentoub merged commit ebaba40 into dotnet:main Sep 29, 2022
@stephentoub stephentoub deleted the cachemorezerotasks branch September 29, 2022 16:44
@ghost ghost locked as resolved and limited conversation to collaborators Oct 29, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants