MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

DOTNET: Memory Optimization in .NET with Span

This is a perfect demo topic. Here’s a single, self-contained console app that lets you feel the difference between:

  • 🚫 Without Span<T> – using Substring (allocates new strings every time)
  • ✅ With Span<T> – using AsSpan + Slice (no extra allocations)

You’ll get timing + GC stats for both in the same run.


1️⃣ Full Code – Program.cs

Copy–paste this as Program.cs (or replace the existing one in a new console app):



2️⃣ (Optional) Minimal .csproj

If you want a fully explicit project file, create SpanDemo.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 change net8.0 to net9.0 or net10.0 depending on your installed SDK.


3️⃣ Step-by-Step: How to Run It

Step 1 – Create a new console app

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

Step 2 – Replace Program.cs

  • Open Program.cs
  • Delete everything
  • Paste the full code from section 1️⃣

(Optionally replace the generated .csproj with the one in 2️⃣.)

Step 3 – Build and run in Release

dotnet run -c Release

You’ll see output similar to:

=========================================
      Span<T> Demo – Substring vs Span    
=========================================

Items to process: 500,000

Preparing test data...
Warming up (small runs)...
--- Warmup – Substring (no Span) ---
Items processed : 50,000
Time Elapsed    : 45 ms
GC Gen0         : 5
GC Gen1         : 0
GC Gen2         : 0
Managed Memory Δ: 2.30 MB
Checksum (ignore, just prevents JIT from optimizing away work): 1234567

--- Warmup – Span<T> ---
Items processed : 50,000
Time Elapsed    : 20 ms
GC Gen0         : 1
GC Gen1         : 0
GC Gen2         : 0
Managed Memory Δ: 0.20 MB
Checksum (ignore, just prevents JIT from optimizing away work): 1234567

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

--- WITHOUT Span<T> – using Substring (allocations) ---
Items processed : 500,000
Time Elapsed    : 400 ms
GC Gen0         : 40
GC Gen1         : 2
GC Gen2         : 0
Managed Memory Δ: 20.50 MB
Checksum (ignore, just prevents JIT from optimizing away work): 1234567

--- WITH Span<T> – using AsSpan + Slice (no extra allocations) ---
Items processed : 500,000
Time Elapsed    : 180 ms
GC Gen0         : 4
GC Gen1         : 0
GC Gen2         : 0
Managed Memory Δ: 1.10 MB
Checksum (ignore, just prevents JIT from optimizing away work): 1234567
Code language: HTML, XML (xml)

(Your exact numbers will vary by machine, but the pattern should be similar.)


4️⃣ How to “Experience” and Interpret the Results

Look at these metrics for each scenario:

  • ⏱ Time Elapsed
  • 🗑 GC Gen0 / Gen1 / Gen2
  • 💾 Managed Memory Δ (MB)

🔴 Scenario 1 – WITHOUT Span<T> (using Substring)

What happens:

  • For each of the 500,000 strings, we call Substringthree times:
    • Each Substring creates a new string allocation on the heap.
    • So we allocate 1.5M strings in the loop.

You’ll typically see:

  • Higher elapsed time
  • Many more Gen0 collections
  • Possibly some Gen1/Gen2 collections
  • Larger Managed Memory Δ

This simulates a typical string parsing / text processing pattern that is allocation-heavy.


🟢 Scenario 2 – WITH Span<T>

What happens:

  • We still have the same 500,000 original strings (same cost as before).
  • But inside the loop we use: ReadOnlySpan<char> span = s.AsSpan(); var part1 = span.Slice(0, 8); var part2 = span.Slice(9, 3); var part3 = span.Slice(span.Length - 10);
  • These are just views (windows) over the same underlying string:
    • No new string objects are created.
    • No extra heap allocations per slice.

You should see:

  • Lower elapsed time (less allocation + less GC work)
  • Much fewer Gen0 collections
  • Gen1/Gen2 often drop to zero
  • Managed Memory Δ is much smaller

This is exactly the benefit of Span<T>:
🔹 Operate on slices of data without additional allocations.


5️⃣ Playing with the Load

To make the impact more dramatic (for demo):

  • Increase item count: const int itemCount = 1_000_000;
  • Or add more slicing and comparisons per string.

Just be aware that very large values can make the Substring scenario quite heavy.


6️⃣ How to Explain This in Training

You can summarize it like this:

  • Without Span<T>, every Substring call allocates a new string. In a tight loop, this leads to tons of small GC’ed objects, more GC cycles, and higher latency.
  • With Span<T>, we use AsSpan + Slice to work with slices of the existing string. No new allocations → lower GC pressure → better throughput.

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

PropRaahi: How a New Property Research Platform Is Tackling India’s Biggest Real Estate Problems

From confusing property documents and hidden costs to unreliable information and buyer uncertainty, PropRaahi wants to make property buying in India more transparent, informed, and buyer-friendly. India’s…

Read More

Why Engineers Click Through Compliance Training – and What DevOps Teams Can Do About It

Ask a room of engineers about their annual compliance module and you will hear the same story: a slide deck on data protection, a few multiple-choice questions,…

Read More

Could An AI Chatbot Help Your Business Deliver Better Customer Support? What To Know About Implementing One

Customers don’t always have the time or patience to wait for answers. From checking delivery times and asking about a service to trying to resolve a problem,…

Read More

How to stop support escalations eating your engineering time

Nobody decides that engineers should do support. It happens one message at a time. A ticket looks odd, L1 isn’t sure, and someone pings the developer who…

Read More

Best Print Driver Management Software for IT Teams in 2027: 7 Tools Compared

Microsoft’s end-of-servicing plan for legacy third-party printer drivers is reshaping how IT teams handle print management. From January 15, 2026, no new printer drivers are published to…

Read More

Switching EOR Providers: How to Protect Your Employees and Keep Work on Track

Changing an employment provider can affect payroll, employee records, benefits and day-to-day support. Without careful planning, even a necessary transition can create uncertainty for international employees. A…

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

This blog explains memory optimization in .NET in a very clear and practical way, especially by highlighting how Span and related structures help reduce allocations and improve application performance. The examples make it easier to understand how better memory handling can directly impact scalability and responsiveness in real-world systems. For developers working on high-performance or resource-sensitive applications, these insights are extremely valuable. Overall, the article bridges the gap between theory and practical coding techniques, making it a useful read for .NET professionals who want to write more efficient and reliable applications.

Jason Mitchell
Jason Mitchell
11 months ago

This article does a great job explaining how using Span<T> and related stack-based data structures in .NET can lead to significant memory and performance gains, especially by avoiding unnecessary heap allocations and reducing garbage-collection overhead. The clear examples and rationale make it easy to understand why stack-allocated memory and slicing can outperform traditional heap-based arrays or collections in many scenarios. For developers focused on high-performance or low-latency applications, these techniques are invaluable. Thanks for sharing such a practical guide — this is definitely a resource worth bookmarking for .NET teams aiming for efficient memory management.

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