runtime icon indicating copy to clipboard operation
runtime copied to clipboard

ValueTask doesn't inline well

Open benaadams opened this issue 9 years ago • 40 comments

None of the method builder or methods on ValueTask seem to inline very well

Inlinee: System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1[System.Decimal].Create - value class System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1<!0> () Fail Reason: Native estimate for function size exceeds threshold.

Inlinee: System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1[System.Decimal].get_Task - instance value class System.Threading.Tasks.ValueTask`1<!0> () Fail Reason: Native estimate for function size exceeds threshold.

Inlinee: System.Runtime.CompilerServices.ValueTaskAwaiter`1[System.Decimal].GetResult - instance !0 () Fail Reason: Native estimate for function size exceeds threshold.

Inliner: TheAwaitingGame.Order+d__5.MoveNext - instance void () Inlinee: instance value class System.Threading.Tasks.ValueTask`1 () Fail Reason: Native estimate for function size exceeds threshold.

Using a ternary check will give better results than a direct await

e.g. (task.IsCompleted) ? task.Result : await task;

Note: should be IsCompletedSuccessfully though the Task.Status path doesn't inline either https://github.com/dotnet/corefx/issues/16745#issuecomment-292728779

Should the no-wait sync path be marked with aggressive inlines?

Or is the state machine going to automatically add more weight than the ternary check?

/cc @stephentoub @AndyAyersMS

benaadams avatar Apr 17 '17 12:04 benaadams

It seems awaiting .AsTask() rather than the ValueTask gives similar results to the ternary check; other than allocations shooting up https://github.com/mgravell/protobuf-net/pull/234

benaadams avatar Apr 17 '17 13:04 benaadams

@benaadams, can you share a small code sample where it's not getting inlined? In a quick one I just threw together, the hot path with ValueTask/ValueTaskAwaiter for a synchronously completed ValueTask is entirely inlined.

stephentoub avatar Apr 17 '17 13:04 stephentoub

@stephentoub its this async call chain https://github.com/mgravell/protobuf-net/blob/async/src/TheAwaitingGame/Program.cs#L144-L152

Perhaps because its ValueTask<decimal>?

benaadams avatar Apr 17 '17 13:04 benaadams

Also was looking at netcoreapp1.1 rather than 2.0 if something has been resolved.

benaadams avatar Apr 17 '17 13:04 benaadams

Might be different issue than not inlining; have annotated the methods; testing all completed paths.

Type              |                 Method |       Mean |     Op/s | Allocated |
----------------- |----------------------- |-----------:|---------:|----------:|
Straight Call     |                   Sync | 12.4577 us | 80271.89 |      0 kB |
Completed Task    |              TaskAsync | 19.5186 us | 51233.10 |  24.25 kB |
ValueTask         |         ValueTaskAsync | 24.1389 us | 41426.95 |      0 kB |
Ternary Check     |  ValueTaskCheckedAsync | 20.5660 us | 48623.86 |      0 kB |
Manual Await Skip |       HandCrankedAsync | 16.3431 us | 61187.91 |      0 kB |

benaadams avatar Apr 17 '17 13:04 benaadams

Might be different issue

Why is the expectation that ValueTask will be faster than a completed task, or am I misunderstanding the concern? I fully expect that there are overheads associated with a ValueTask, e.g. it stores multiple fields that are returned, it has an extra branch, etc. This is why when I've been asked whether every method should just return a ValueTask<T> instead of a Task<T>, my answer has never been yes and rather it depends on how often an asynchronous completion is expected, whether all T results could be cached, etc., as well as partially why there's no non-generic ValueTask (i.e. it's no better than just returning a completed task).

stephentoub avatar Apr 17 '17 13:04 stephentoub

If Task<T>.FromResult() is faster than ValueTask<T>, in what cases would it be useful to use ValueTask<T>?

mattnischan avatar Apr 17 '17 14:04 mattnischan

If Task.FromResult() is faster than ValueTask, in what cases would it be useful to use ValueTask?

"faster" is very subjective. FromResult() allocates a Task<T>, so while it may be "faster" to get the object then and there, you're building up GC debt that'll be paid in spades later.

stephentoub avatar Apr 17 '17 14:04 stephentoub

Has there been any benchmarks done where the GC is under pressure from other work while still benchmarking the Task vs ValueTask?

I imagine that your GC will have a max throughput on your system, and if possible, it might be worth offloading this to the stack. I imagine that it will also have a positive effect on long tail latency, as the value task perf will be more consistent with less variations over time. e.g. in Kestrel webserver.

Would that be a valid assumption to make?

rogeralsing avatar Apr 17 '17 14:04 rogeralsing

Would that be a valid assumption to make?

That's the whole reason ValueTask<T> exists: to minimize allocation in cases where it's expected that an asynchronous method will frequently complete synchronously with arbitrary result values (e.g. T is an Int32 and possible results span the Int32 range such that it would be infeasible to cache a Task<T> for all of them). Common example would be Stream.ReadAsync: if we had it to do over today, I expect we'd have defined this to return ValueTask<int> rather than Task<int>.

stephentoub avatar Apr 17 '17 14:04 stephentoub

I suspected that would be the answer, but it still strikes me that most use cases are within this particular area, where ValueTask<T> is a representation of some kind of mostly-always-fast-but-occasionally-not type of value, from, say, a data access layer with caching or something like that.

It's possible this test is just not very illustrative of when ValueTask<T> normally wins, i.e. when you're hitting the GC a lot harder than this benchmark is.

mattnischan avatar Apr 17 '17 14:04 mattnischan

It's possible this test is just not very illustrative

GC impact compounds and often doesn't show up in full force in microbenchmarks. The more work you have going on in a real scenario, the more allocation affects things globally in the app.

most use cases are within this particular area

There are definitely many of them, which is why ValueTask<T> was introduced. But there are also common cases where it's not valuable, e.g. it's pretty common to have an asynchronous operation that returns a bool (imagine an asynchronous enumerable with a MoveNextAsync), and for that, both values (true and false) can be cached in Task<bool>s such that there's no benefit to using a ValueTask<bool>.

stephentoub avatar Apr 17 '17 14:04 stephentoub

(All that said, if there are ways we can improve the performance of ValueTask<T>, of course we want to do that. @benaadams, I'm looking at you :smile:)

stephentoub avatar Apr 17 '17 14:04 stephentoub

Heuristic inlining cost estimates for ValueTask<T> where T is a value class will be dependent on T in various complex ways (sizeof(T), whether the jit thinks a T is promotable, etc). So decimal vs some other type may show inlining differences.

Heuristics should be more or less the same for 1.1 vs 2.0.

Inlining of methods that take or return value classes should provide some extra benefit because quite often caller-side struct copy/init code can be removed. But the jit's optimizer is not always able to clean these things up and so the inliner can't yet anticipate that it will do so.

AndyAyersMS avatar Apr 17 '17 16:04 AndyAyersMS

There are 4 methods that don't like inlining; am investigating best approach.

Fighting with the cli and publishing 2.0 atm 😢 , so I can look at the breakout

benaadams avatar Apr 17 '17 16:04 benaadams

Yep, changing the ValueTask type to a reference type instead brings the inlining back to life: https://github.com/mgravell/protobuf-net/pull/235

mattnischan avatar Apr 17 '17 17:04 mattnischan

@stephentoub It will great if you write some blogs about ValueTask at https://blogs.msdn.microsoft.com/pfxteam/. Just a humble request 😀

imranbaloch avatar Apr 17 '17 19:04 imranbaloch

Can see why its doing what its doing, some of this stuff is pretty big 😄

benaadams avatar Apr 18 '17 03:04 benaadams

Will take a while to resolve this as isn't striaghtforward; @karelz want to assign to me? @stephentoub has :trollface:'d my ego into it

benaadams avatar Apr 18 '17 21:04 benaadams

Mwahahahaha

stephentoub avatar Apr 18 '17 21:04 stephentoub