Skip to content

Instantly share code, notes, and snippets.

@BornaGajic
Last active November 6, 2022 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BornaGajic/3a7b9ba69ac372cd92ccff85f34d933f to your computer and use it in GitHub Desktop.
Save BornaGajic/3a7b9ba69ac372cd92ccff85f34d933f to your computer and use it in GitHub Desktop.
ValueTask vs Task benchmark
using BenchmarkDotNet.Attributes;
namespace Sandbox
{
[MemoryDiagnoser]
[ShortRunJob]
public class Benchmarks
{
/// <summary>
/// 1 in 2 is async, returns Task<int>
/// </summary>
[Benchmark]
public async Task<int> CalculateAsync_1_In_2_Async_Task()
{
var retResult = 0;
for(int item = 1; item <= 10_000; item++)
{
retResult += await GetNextAsync_Task(item, 2);
}
return retResult;
}
/// <summary>
/// 1 in 100 is async, returns Task<int>
/// </summary>
[Benchmark]
public async Task<int> CalculateAsync_1_In_100_Async_Task()
{
var retResult = 0;
for (int item = 1; item <= 10_000; item++)
{
retResult += await GetNextAsync_Task(item, 100);
}
return retResult;
}
private async Task<int> GetNextAsync_Task(int token, int asyncFrequency)
{
if (token % asyncFrequency == 0)
{
return await GetInt();
}
return token;
}
/// <summary>
/// 1 in 2 is async, returns ValueTask<int>
/// </summary>
[Benchmark]
public async Task<int> CalculateAsync_1_In_2_Async_ValueTask()
{
var retResult = 0;
for(int item = 1; item <= 10_000; item++)
{
retResult += await GetNextAsync_ValueTask(item, 2);
}
return retResult;
}
/// <summary>
/// 1 in 100 is async, returns ValueTask<int>
/// </summary>
[Benchmark]
public async Task<int> CalculateAsync_1_In_100_Async_ValueTask()
{
var retResult = 0;
for (int item = 1; item <= 10_000; item++)
{
retResult += await GetNextAsync_ValueTask(item, 100);
}
return retResult;
}
private async ValueTask<int> GetNextAsync_ValueTask(int token, int asyncFrequency)
{
if (token % asyncFrequency == 0)
{
return await GetInt();
}
return token;
}
private async Task<int> GetInt()
{
await Task.Yield();
return Random.Shared.Next(1, 100);
}
}
}
using BenchmarkDotNet.Running;
using Sandbox;
var summary = BenchmarkRunner.Run<Benchmarks>();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment