https://github.com/arnab-developer/task-vs-valuetask
Comparison between 'Task' and 'ValueTask'
https://github.com/arnab-developer/task-vs-valuetask
Last synced: 2 months ago
JSON representation
Comparison between 'Task' and 'ValueTask'
- Host: GitHub
- URL: https://github.com/arnab-developer/task-vs-valuetask
- Owner: Arnab-Developer
- License: mit
- Created: 2022-03-06T07:57:24.000Z (over 4 years ago)
- Default Branch: main
- Last Pushed: 2022-05-13T04:00:40.000Z (about 4 years ago)
- Last Synced: 2025-01-17T02:24:11.264Z (over 1 year ago)
- Language: C#
- Homepage:
- Size: 18.6 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.txt
Awesome Lists containing this project
README
# Task vs ValueTask
Comparison between `Task` and `ValueTask` in C#.
If your code's execution path is synchronous in most of the cases and sometimes asynchronous then you can use `ValueTask` to reduce some memory allocation. But if your code's execution path is always asynchronous then `Task` should be used. Because in that case we will not get any performance benefit by using `ValueTask` over `Task`.
## Benchmark comparison result
Benchmark comparison result of the code which is always asynchronous.
```
// * Summary *
BenchmarkDotNet=v0.13.1, OS=Windows 10.0.22000
Intel Xeon Platinum 8272CL CPU 2.60GHz, 1 CPU, 2 logical and 2 physical cores
.NET SDK=6.0.200
[Host] : .NET 6.0.2 (6.0.222.6406), X64 RyuJIT
DefaultJob : .NET 6.0.2 (6.0.222.6406), X64 RyuJIT
| Method | Mean | Error | StdDev | Median | Allocated |
|------------------ |--------:|---------:|---------:|--------:|----------:|
| ReadWithTask | 1.171 s | 0.0325 s | 0.0884 s | 1.215 s | 205 KB |
| ReadWithValueTask | 1.191 s | 0.0248 s | 0.0654 s | 1.219 s | 205 KB |
```
Benchmark comparison result of the code which is 99% of the times synchronous and 1% of time asynchronous.
```
// * Summary *
BenchmarkDotNet=v0.13.1, OS=Windows 10.0.22000
Intel Xeon Platinum 8272CL CPU 2.60GHz, 1 CPU, 2 logical and 2 physical cores
.NET SDK=6.0.200
[Host] : .NET 6.0.2 (6.0.222.6406), X64 RyuJIT
DefaultJob : .NET 6.0.2 (6.0.222.6406), X64 RyuJIT
| Method | Mean | Error | StdDev | Gen 0 | Allocated |
|------------------ |--------:|---------:|---------:|------------:|----------:|
| ReadWithTask | 4.123 s | 0.0511 s | 0.0478 s | 513000.0000 | 9 GB |
| ReadWithValueTask | 3.738 s | 0.0167 s | 0.0157 s | 128000.0000 | 2 GB |
```
## References
- https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.valuetask
- https://www.youtube.com/watch?v=IN4dRdKlISI
- https://www.youtube.com/watch?v=mEhkelf0K6g