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 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 a DevOps/SRE/DevSecOps/Cloud Expert passionate about sharing knowledge and experiences. I have worked at <a href="https://www.cotocus.com/">Cotocus</a>. I share tech blog at <a href="https://www.devopsschool.com/">DevOps School</a>, travel stories at <a href="https://www.holidaylandmark.com/">Holiday Landmark</a>, stock market tips at <a href="https://www.stocksmantra.in/">Stocks Mantra</a>, health and fitness guidance at <a href="https://www.mymedicplus.com/">My Medic Plus</a>, product reviews at <a href="https://www.truereviewnow.com/">TrueReviewNow</a> , and SEO strategies at <a href="https://www.wizbrand.com/">Wizbrand.</a> Do you want to learn <a href="https://www.quantumuting.com/">Quantum Computing</a>? <strong>Please find my social handles as below;</strong> <a href="https://www.rajeshkumar.xyz/">Rajesh Kumar Personal Website</a> <a href="https://www.youtube.com/TheDevOpsSchool">Rajesh Kumar at YOUTUBE</a> <a href="https://www.instagram.com/rajeshkumarin">Rajesh Kumar at INSTAGRAM</a> <a href="https://x.com/RajeshKumarIn">Rajesh Kumar at X</a> <a href="https://www.facebook.com/RajeshKumarLog">Rajesh Kumar at FACEBOOK</a> <a href="https://www.linkedin.com/in/rajeshkumarin/">Rajesh Kumar at LINKEDIN</a> <a href="https://www.wizbrand.com/rajeshkumar">Rajesh Kumar at WIZBRAND</a> <a href="https://www.rajeshkumar.xyz/dailylogs">Rajesh Kumar DailyLogs</a>

Related Posts

Ruby on Rails vs Node.js: Performance, Speed, and Scalability Compared

Choosing between Ruby on Rails and Node.js is a common decision when building modern web applications. Both frameworks power large-scale products, but they approach performance, concurrency, and…

Read More

How Zero-Knowledge Coprocessors Are Reshaping Web3 Computation

Developers often hit a brick wall when building decentralized apps. Standard infrastructure just fails to keep up. Clogging a main network with heavy workloads leads to slow…

Read More

5 Top Developer Experience (DevEx) Insight Tools for 2026

Developer experience has evolved from an internal engineering concern into a measurable operational discipline. As software organizations scale across distributed cloud environments, platform engineering initiatives, AI-assisted development…

Read More

Top 10 AI Tools to Automate Repetitive Documents For DevOps Teamsย 

DevOps teams have automated deployingโ€š testingโ€š monitoringโ€š and rolling back changesโ€š but documentation layer automation is a gap that still incurs time costโ€ค Gartner predicts by 2026…

Read More

Customer Loyalty Strategy for SaaS and eCommerce: How to Pick the Right Software

Customer Loyalty Strategy for SaaS and eCommerce: How to Pick the Right Software TL;DR Retaining a customer costs 5 to 25 times less than acquiring a new…

Read More

Top 10 Sales Enablement Tools: Features, Pros, Cons & Comparison

Introduction Sales Enablement Tools are platforms designed to equip sales teams with the right content, insights, training, and data at the right timeโ€”so they can sell more…

Read More
Subscribe
Notify of
guest
2 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Skylar Bennett
Skylar Bennett
5 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
5 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