String Optimization in .NET core

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:

Image for post
Image for post

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.

Image for post
Image for post

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


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

Hope you guys enjoyed reading this. Happy coding :)

I am fascinated when two applications talk.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store