Find the Best Cosmetic Hospitals

Explore trusted cosmetic hospitals and make a confident choice for your transformation.

โ€œInvest in yourself โ€” your confidence is always worth it.โ€

Explore Cosmetic Hospitals

Start your journey today โ€” compare options in one place.

DOTNET: Memory Optimization in .NET with ValueTask

Hereโ€™s a single, self-contained console app that lets you experience the difference between:

  • ๐Ÿšซ Without ValueTask โ€“ using async Task<int> (allocates a Task even on fast sync path)
  • โœ… With ValueTask โ€“ returning synchronously without allocating when value is cached

Youโ€™ll see timing + GC stats for both in the same run.


1๏ธโƒฃ Full Code โ€“ Program.cs


This is <strong>100% self-contained</strong> โ€“ no extra packages needed.Code language: HTML, XML (xml)

2๏ธโƒฃ Optional โ€“ Minimal .csproj

If you want to control the target framework explicitly, create ValueTaskDemo.csproj:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>
Code language: HTML, XML (xml)

You can switch to net9.0 or net10.0 if youโ€™re targeting .NET 9/10 SDK.


3๏ธโƒฃ Step-by-Step: How to Run It

Step 1 โ€“ Create a new console project

dotnet new console -n ValueTaskDemo
cd ValueTaskDemo
Code language: JavaScript (javascript)

Step 2 โ€“ Replace Program.cs

  • Open Program.cs in your editor
  • Delete everything
  • Paste the full code from section 1๏ธโƒฃ

(Optionally replace the generated .csproj with the file in 2๏ธโƒฃ.)

Step 3 โ€“ Build and run in Release mode

dotnet run -c Release

Youโ€™ll see output similar to:

=========================================
   ValueTask Demo โ€“ Task vs ValueTask    
=========================================

Iterations : 5,000,000
Cache size : 1,000
Scenario   : All calls hit the FAST (cached) path.

Warming up (small runs)...
--- Warmup โ€“ async Task<int> ---
Iterations        : 500,000
Time Elapsed      : 80 ms
GC Gen0           : 10
GC Gen1           : 0
GC Gen2           : 0
Managed Memory ฮ”  : 3.20 MB
Checksum (ignore) : 499500000

--- Warmup โ€“ ValueTask<int> ---
Iterations        : 500,000
Time Elapsed      : 45 ms
GC Gen0           : 3
GC Gen1           : 0
GC Gen2           : 0
Managed Memory ฮ”  : 0.70 MB
Checksum (ignore) : 499500000

=========== REAL TESTS (Release) ==========

--- WITHOUT ValueTask โ€“ async Task<int> ---
Iterations        : 5,000,000
Time Elapsed      : 800 ms
GC Gen0           : 100
GC Gen1           : 5
GC Gen2           : 0
Managed Memory ฮ”  : 30.50 MB
Checksum (ignore) : 4995000000

--- WITH ValueTask โ€“ ValueTask<int> ---
Iterations        : 5,000,000
Time Elapsed      : 430 ms
GC Gen0           : 15
GC Gen1           : 0
GC Gen2           : 0
Managed Memory ฮ”  : 5.10 MB
Checksum (ignore) : 4995000000
Code language: HTML, XML (xml)

(Exact numbers will vary per machine, but the pattern should be similar.)


4๏ธโƒฃ How to โ€œExperienceโ€ and Interpret the Results

Focus on these for each scenario:

  • โฑ Time Elapsed
  • ๐Ÿ—‘ GC Gen0 / Gen1 / Gen2
  • ๐Ÿ’พ Managed Memory ฮ”

๐Ÿ”ด Scenario 1 โ€“ WITHOUT ValueTask (async Task)

public async Task<int> GetValueAsync(int key)
{
    if (_cache.TryGetValue(key, out var value))
    {
        return value; // looks sync, but method is async
    }

    await Task.Delay(1).ConfigureAwait(false);
    return key;
}
Code language: JavaScript (javascript)

Even when the value is immediately available in cache, the compiler:

  • Generates an async state machine
  • Allocates a Task object for each call

In a tight loop with millions of calls, youโ€™ll see:

  • Higher Time Elapsed
  • More GC Gen0 collections
  • Higher Managed Memory ฮ” (more allocations)

๐ŸŸข Scenario 2 โ€“ WITH ValueTask (ValueTask)

public ValueTask<int> GetValueAsync(int key)
{
    if (_cache.TryGetValue(key, out var value))
    {
        return new ValueTask<int>(value); // completes synchronously, no Task allocation
    }

    return new ValueTask<int>(SlowPathAsync(key)); // real Task only on slow path
}
Code language: PHP (php)

Now:

  • For the fast path (cache hit), we:
    • Do not create a Task
    • Do not create a state machine
  • We only use a real Task<int> on the slow path (SlowPathAsync), which weโ€™re not hitting in this benchmark.

In the output, you should see:

  • Lower elapsed time (less allocation + less GC work)
  • Much fewer Gen0 collections
  • Smaller Managed Memory ฮ”

This is exactly the use case where ValueTask shines:
A method that is often synchronous but must expose an async API.


5๏ธโƒฃ Tweaks to Make the Effect More Visible

You can tune:

  • iterations (e.g., 10_000_000 if your machine is strong)
  • cacheSize (smaller cache keeps hit ratio at 100%)
const int iterations = 10_000_000;
const int cacheSize = 100;
Code language: JavaScript (javascript)

This increases the number of fast-path calls and magnifies the Task vs ValueTask difference.


Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

OWASP Dependency-Check โ€” 1-Hour Quick Demo Lab

Level: Beginner / Basic DevSecOpsDuration: 60 minutesFormat: Instructor-led hands-on demoFocus: Install โ†’ scan a real project โ†’ read findings โ†’ understand CVE/CVSS โ†’ generate reports โ†’ demonstrate a simple security gate…

Read More

OWASP Dependency-Checkย – Hands-On Lab Manual

OWASP Dependency-Check 13.0.0 Basic-to-Essentials Hands-On Lab Manual Audience: Beginners and engineers with basic DevOps/DevSecOps knowledgeTutorial verified/researched on: 2026-10-03OWASP Dependency-Check version: 13.0.0Minimum Java supported by Dependency-Check: Java 11Recommended lab Java runtime: Java 17…

Read More

Manufacturing automation: Is it worth investing in the field of manufacturing automation?

An investment in manufacturing automation can pay off. (Photo: Generated with the help of AI) Manufacturing automation has developed from a solution mainly associated with large factories…

Read More

How to Choose a Virtual Machine for Development and Production Workloads

Virtual machines remain a practical building block for development, testing, staging, production services, and infrastructure automation. The challenge is not simply choosing the largest instance available. It…

Read More

System Mechanic vs Advanced SystemCare for Small Teams Without an MDM

If you’re keeping a handful of Windows workstations or test machines healthy without a device-management platform, iolo’s System Mechanic is the better choice over IObit’s Advanced SystemCare…

Read More

How to Plan Infrastructure for a Community Project

Every thriving community project sits on top of infrastructure nobody notices, right up until it breaks. The forum. The server. The backups. The dull plumbing that holds…

Read More
Subscribe
Notify of
guest
2 Comments
Newest
Oldest Most Voted
Skylar Bennett
Skylar Bennett
9 months ago

This blog clearly explains how using ValueTask can help optimize memory usage and improve performance in .NET applications, especially in high-throughput or asynchronous scenarios. It highlights when ValueTask is a better choice than Task and cautions readers about proper usage to avoid common pitfalls. The practical focus on reducing allocations and improving efficiency makes the content very relevant for developers building scalable and responsive systems. Overall, the article provides useful guidance for .NET professionals who want to make informed design decisions and write more performance-aware asynchronous code.

Jason Mitchell
Jason Mitchell
10 months ago

This article provides a very clear explanation of how ValueTask can significantly improve memory efficiency in .NET applications, especially in scenarios where asynchronous operations often complete synchronously. By reducing unnecessary heap allocations and lowering GC pressure, ValueTask becomes a powerful tool for developers working on high-performance or high-frequency code paths. I appreciate how the blog highlights not only the benefits but also the correct usage patterns, helping readers understand when ValueTask is appropriate and when a regular Task is still the better choice. Overall, this is a very practical and insightful guide for anyone looking to optimize memory usage and improve the responsiveness of their .NET applications.

2
0
Would love your thoughts, please comment.x
()
x