C# Tips

Improving C# Performance by Using AsSpan and Avoiding Substring

By   Sunday, October 22, 2023 comments
reads
React:
During development and everyday use, Substring is often the go-to choice for string manipulation. However, there are cases where Substring can negatively impact performance and result in unnecessary string memory allocation. 
In this article, we will explore how to enhance the performance of C# applications by making informed decisions when working with substrings. 
We'll compare the traditional Substring method with the newer AsSpan method and discuss when to use each for maximum efficiency

C# AsSpan VS Substring

Substring()

The Substring method is a commonly used tool for extracting substrings from a string in C#. While it's convenient and easy to use.
I have created a sample method that takes a full date string, splits the string, and returns the day, month, and year separated by commas.

🐌 Memory Allocation

When you call Substring, it creates a new string object and copies the characters from the original string to the new substring.

Improving C# Performance by Using AsSpan and Avoiding Substring

This can result in additional memory allocations, which can be problematic, particularly when handling large strings or frequent substring operations.

AsSpan

In contrast to Substring, the AsSpan method returns a ReadOnlySpan from the original string. A ReadOnlySpan is a lightweight, stack-allocated view over the data, and it doesn't create a new string object or copy the characters.

Same date full string convert into AsSpan method

πŸš€ Improved Performance: 

By using AsSpan, you can significantly improve the performance of your code. It eliminates the overhead associated with creating new string objects and copying characters, making it an excellent choice for scenarios where performance is critical.

Reduced Memory Overhead: The lack of memory copying in AsSpan means that your application consumes less memory, reducing the load on the garbage collector and leading to a more efficient use of resources. You can refer to the statistics below for the results of the two methods.

Improving C# Performance by Using AsSpan and Avoiding Substring

When I can use AsSpan

The AsSpan method is particularly valuable in situations where you need to work with portions of a string without the need for actual string manipulation. Here are some common scenarios where using AsSpan is recommended

πŸ’‘ API Compatibility: 

Many APIs that accept strings now have overloads that accept a ReadOnlySpan argument. When such overloads are available, you can improve performance by calling AsSpan instead of Substring.

Performance-Critical Operations:

If your application performs extensive string manipulation operations, consider using AsSpan for better performance.

When I can use Substring

It's essential to note that there are still situations where using  Substring may be appropriate

✅ Creating a Copy

If you need to create a distinct copy of the substring (rather than a view), Substring remains a suitable choice.

Conclusion

In C# programming, optimizing string manipulation is crucial for enhancing the performance of your applications. While `Substring` is a well-known method for extracting substrings, it can introduce unnecessary memory overhead and reduce performance in some scenarios. On the other hand, `AsSpan` offers a lightweight, memory-efficient alternative that can significantly boost your application's speed. I hope this article more help you to 


SJ
Suthahar Jegatheesan

Senior Solutions Architect · Microsoft Azure, AI & Mobile. Author of the Xamarin Q&A Book.

More in this series

No comments:

sponsored

What Colleagues Say

“Suthahar is one of the most thorough and knowledgeable cloud architects I’ve worked with. His depth on Azure and ability to make complex mobile solutions work cross-platform is remarkable. He always delivers beyond expectations.”

AT Arun T. Senior Engineering Manager · Direct Manager

“I’ve followed Suthahar’s MSDEVBUILD blog for years — practical, deep, always current. Working alongside him confirmed what I suspected: he’s as sharp in person as on paper, and a genuinely generous mentor and architect.”

RK Rajesh K. Lead Developer · Mindtree

Certifications & Recognition

AZ-300 · Azure Architect Technologies AZ-301 · Azure Architect Design AZ-104 · Azure Administrator Associate AI-100 · Designing Azure AI Solutions DP-900 · Azure Data Fundamentals MCPD · Windows Phone Certified SAFe® 4 Scrum Master

Technical Expertise

☁ Cloud Platforms Microsoft Azure — Expert · 18 yrs App Services · AKS · Functions · Cosmos DB · APIM · Entra ID AWS & Google Cloud — Advanced
πŸ€– AI & Automation Azure OpenAI / GenAI — Advanced · 5 yrs RAG Pipelines · Bot Framework · Cognitive Services · Vision & Speech AI · ML.NET
πŸ“± Mobile Architecture .NET MAUI & Xamarin — Expert · 12 yrs Flutter · Native iOS/Android · Offline-First · Secure Storage & Auth
πŸ”’ Identity & Security Microsoft Entra ID — Expert OAuth 2.0 · OIDC · Zero Trust · Conditional Access · RBAC · Key Vault

Speaking & Community

Microsoft User Group Malaysia Recurring speaker on Azure architecture, AI integration and .NET mobile development across Malaysia and APAC.
Global Azure Bootcamp — Chennai Presented “AI into Xamarin Mobile Apps” at GAB Chennai, part of the worldwide Global Azure community event.
AI & Azure OpenAI Community Events Workshops and live demos on RAG pipelines, AI agents and intelligent workflow automation since 2023.
Mobile & Cloud Workshops — Coimbatore Multi-day deep-dive sessions at GRG Computer Technology, KG Microsoft Innovation Center and RVS College of Arts and Science.
500+Blog Articles
50+Conference Talks
10K+Monthly Readers
30Public Repositories
3Continents Delivered
MSDEVBUILD Assistant Ask about Suthahar, Azure, AI or mentorship
Hi! I’m a simple FAQ bot for MSDEVBUILD. Tap a question below or type your own.