AsSpan vs Substring
🔎 Explanation of AsSpan vs. Substring
💡 When working with strings in C#, choosing between Substring and AsSpan can significantly affect the performance and memory usage of your code, especially in scenarios involving large strings or frequent substring operations.
1. Substring
🔦 Definition: The Substring method creates a new string that is a copy of a specified part of an original string.
🕯️ Behavior: It allocates memory for the new string, copying characters from the original string. This can lead to increased memory usage and garbage collection overhead since multiple string objects may be created.
💉 Usage: string substring = originalString.Substring(startIndex, length);
2. AsSpan
🔦 Definition: The AsSpan method, on the other hand, returns a ReadOnlySpan<char> representation of the original string without creating a new string or copying characters.
🕯️ Behavior: ReadOnlySpan is a stack-allocated view of the data that allows you to work with a portion of the string efficiently. It’s lightweight and reduces memory overhead.
💉Usage: ReadOnlySpan<char> span = originalString.AsSpan(startIndex, length);
Get Sina Riyahi’s stories in your inbox
Join Medium for free to get updates from this writer.
Substring
✅ Pros:
✔️ Creates a new string, which is useful if you need to manipulate the resulting substring as a separate string instance.
Works with APIs and methods that expect a string type.
⛔ Cons:
❌ Memory allocation for new string objects can lead to performance overhead.
Frequent calls in large loops or with large strings can lead to increased pressure on the garbage collector.
AsSpan
✅ Pros:
✔️ No new allocation of string objects, leading to better performance, especially in scenarios where substrings are created frequently.
Lightweight and more efficient in terms of memory usage.
Ideal for scenarios where you don’t need the substring as a separate string but just want to read characters.
⛔ Cons:
❌ Cannot be assigned to a string type directly — needs to be converted back into a string if you require a mutable string.
Limited to read-only operations; you can’t modify the data in the span.
💡 when you’re dealing with string manipulations in C#, it’s advantageous to prefer ReadOnlySpan<char> (via AsSpan) for better performance and memory efficiency, especially when you don’t need to alter the substring. However, Substring remains a valid choice when you need a distinct, mutable string object. Always choose based on the specific needs of your code and the context in which you’re working.






