String Optimization in .NET core

Sumeet More
2 min readDec 25, 2020

--

This is micro post on string optimization in .NET core. Let’s begin.

Strings are immutable in .NET world. Due to which every time you create string, new allocation occurs. Because of this more and more memory is used, ultimately increasing GC pressure. And when GC is triggered, there is a GC pause which indirectly affects performance of the application.

Let’s take an example to see difference.

Problem statement : Write a program to add first 10,000 numbers which are represented in comma separated string (eg: if input = “1,2,3” then final result will be 6)

Normal/Classic version:

Optimized version: In .NET core, there is new data structure called Span<T>which is like a smart pointer. So if one wants substring from original string , instead of creating new string — this smart pointer(span) will give reference to that substring. Now let’s use Span<T> in our problem statement.

Code is little complicated. We are tracking start position, trying to detect comma and take slice of that.

Benchmarks:

We can see, Span<T> version outperforms normal/classic version and allocates way less.

Hope you guys enjoyed reading this. Happy coding :)

--

--

Sumeet More
Sumeet More

Written by Sumeet More

Software Engineer 2 at Microsoft | Backend Engineer and Architect| Blockchain & ML enthusiast | C#,.NET Core, Rust, Javascript and Go

Responses (1)