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 Object Pooling

Hereโ€™s a single, self-contained console app you can run to see and feel the difference between:

  • ๐Ÿšซ Without Object Pooling (allocate new arrays every time)
  • โœ… With Object Pooling (reuse arrays via ArrayPool<byte>)

It includes:

  • Full Program.cs code
  • Optional .csproj (if you want a drop-in project)
  • Step-by-step how to run
  • How to interpret the results

Works on any modern .NET (7/8/9/10+).


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


2๏ธโƒฃ Optional โ€“ Minimal .csproj (if you want full project file)

Create a file named ObjectPoolingDemo.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 also change net8.0 to net9.0 or later (e.g., net10.0) depending on your installed SDK.


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

Step 1 โ€“ Make a new console project

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

Step 2 โ€“ Replace Program.cs

Open Program.cs in your editor and replace everything with the code from section 1๏ธโƒฃ.

(Optionally replace the autogenerated .csproj with the one in 2๏ธโƒฃ, but not required.)

Step 3 โ€“ Build and run in Release

dotnet run -c Release

Youโ€™ll see output like:

=========================================
   Object Pooling Demo (ArrayPool<byte>)  
=========================================

Iterations : 1,000,000
BufferSize : 1024 bytes

Warming up JIT (small runs)...
--- Warmup - Without Pooling ---
Iterations: 100,000, BufferSize: 1024 bytes
Time Elapsed : 120 ms
GC Gen0      : 12
GC Gen1      : 1
GC Gen2      : 0
Managed Memory Delta (approx): 3.40 MB
Checksum (ignore, just to keep JIT honest): 123456789

--- Warmup - With Pooling ---
Iterations: 100,000, BufferSize: 1024 bytes
Time Elapsed : 60 ms
GC Gen0      : 2
GC Gen1      : 0
GC Gen2      : 0
Managed Memory Delta (approx): 0.20 MB
Checksum (ignore, just to keep JIT honest): 123456789

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

--- WITHOUT pooling (new byte[] each time) ---
Iterations: 1,000,000, BufferSize: 1024 bytes
Time Elapsed : 900 ms
GC Gen0      : 100
GC Gen1      : 5
GC Gen2      : 1
Managed Memory Delta (approx): 40.00 MB
Checksum (ignore, just to keep JIT honest): 123456789

--- WITH pooling (ArrayPool<byte>.Shared) ---
Iterations: 1,000,000, BufferSize: 1024 bytes
Time Elapsed : 400 ms
GC Gen0      : 5
GC Gen1      : 0
GC Gen2      : 0
Managed Memory Delta (approx): 2.00 MB
Checksum (ignore, just to keep JIT honest): 123456789
Code language: HTML, XML (xml)

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


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

Focus on these lines for each scenario:

  1. Time Elapsed
  2. GC Gen0 / Gen1 / Gen2
  3. Managed Memory Delta (MB)

๐Ÿ”ด Scenario: WITHOUT pooling

  • new byte[bufferSize] is executed 1,000,000 times.
  • That means ~1,024 * 1,000,000 โ‰ˆ 1 GB worth of arrays allocated over time.
  • You should see:
    • Higher elapsed time
    • Many more Gen0 collections
    • Possibly some Gen1/Gen2 collections
    • A larger memory delta

This simulates a real-world high-allocation hot path (e.g., per-request/per-message allocations).


๐ŸŸข Scenario: WITH pooling (ArrayPool.Shared)

  • Arrays are rented and returned from a shared pool.
  • Only a small number of underlying arrays are actually allocated.
  • Subsequent rents reuse these buffers.

Expected result:

  • Lower elapsed time (less GC interference + fewer allocations)
  • Much fewer Gen0 collections, often 5โ€“10x fewer
  • Gen1/Gen2 collections may drop to 0 or near 0
  • Managed Memory Delta much smaller

You are literally seeing GC pressure decreasing because:

  • Without pooling โ†’ allocate, discard, GC must clean up
  • With pooling โ†’ allocate a few times, then reuse, GC is mostly idle

5๏ธโƒฃ Tweaking the Demo to Feel the Effect More

If you want even more dramatic differences:

  • Increase iterations (e.g., 5_000_000)
  • Or increase bufferSize (e.g., 4096 or 16_384)
const int iterations = 5_000_000;
const int bufferSize = 4096;
Code language: JavaScript (javascript)

โš ๏ธ Be careful: this can make the non-pooled version quite heavy on CPU and memory. Good for a demo on a strong machine, but maybe too much on low-end hardware.


6๏ธโƒฃ How to Understand in Training

You can summarize for your audience:

โ€œIn the no pooling scenario, we allocate a fresh buffer for each iteration, forcing the GC to keep cleaning up.
In the pooling scenario, we reuse buffers from ArrayPool<byte>.Shared, dramatically reducing allocations and GC work.
The difference in GC counts and elapsed time is the direct impact of object pooling.โ€

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 article does a great job of showing how object pooling can be used as a practical performance strategy in .NET applications. By reusing objects instead of creating and disposing them repeatedly, developers can lower memory allocations and reduce the overhead of frequent garbage collection. The explanation makes it clear that object pooling is especially useful in high-throughput and long-running services. Overall, the blog helps readers understand when object pooling makes sense and how it can contribute to building stable, high-performance .NET systems.

Jason Mitchell
Jason Mitchell
5 months ago

This article gives a very clear and practical explanation of how object pooling can help .NET applications reuse instances instead of constantly allocating and discarding them โ€” a tactic that can greatly reduce memory churn and improve performance in high-load environments. The examples and scenarios described make it easy to see when object pooling is most beneficial โ€” especially for expensive-to-create objects or frequently used resources โ€” and why it matters for scalability and efficiency. I appreciate how the post balances theory with actionable advice that developers can implement right away. Overall, this is a valuable resource for anyone working on optimizing resource usage and responsiveness in .NET applications.

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