Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio
C#

C#: Use Span for High-Performance Memory Access Without Allocation

- 28.05.26 - ErcanOPAK

⚡ Zero-Allocation Slicing

Span<T> gives a view into memory without copying. No allocations, no GC pressure. Ideal for parsing, string manipulation, and high-performance scenarios.

❌ Allocating Substring

// Allocates new string (GC pressure)
string data = "123,456,789";
string first = data.Substring(0, 3);  // New string allocation
string second = data.Substring(4, 3); // Another allocation
// 1000 operations = 1000 allocations, GC collects constantly

✅ Span View (No Allocation)

ReadOnlySpan<char> data = "123,456,789";
ReadOnlySpan<char> first = data.Slice(0, 3);   // View, no allocation
ReadOnlySpan<char> second = data.Slice(4, 3);  // View, no allocation
// 1000 operations = 0 allocations, zero GC pressure

🎯 Practical Examples

// Parse CSV line without allocations
ReadOnlySpan<char> line = "John,Doe,30,Engineer";
int start = 0;
for (int i = 0; i < line.Length; i++)
{
    if (line[i] == ',')
    {
        var field = line.Slice(start, i - start);
        ProcessField(field);  // No string allocation!
        start = i + 1;
    }
}

// Fast number parsing from span
ReadOnlySpan<char> number = "12345";
if (int.TryParse(number, out int value))
{
    Console.WriteLine(value);  // No temporary string
}

// Working with byte arrays
byte[] buffer = new byte[1024];
Span<byte> span = buffer.AsSpan();
span[0] = 0xFF;
span[1] = 0xAA;

// Stack allocation (ultra-fast, no heap)
Span<int> numbers = stackalloc int[100];
for (int i = 0; i < numbers.Length; i++)
{
    numbers[i] = i * 2;
}

✅ Real-World Performance Gain

// Without Span (allocates 1,000,000 strings)
string data = GetLargeString();
for (int i = 0; i < 1000000; i++)
{
    string part = data.Substring(i, 10);
    Process(part);  // 1M allocations, GC thrashing
}
// Execution time: 5 seconds, GC collects every second

// With Span (zero allocations)
ReadOnlySpan<char> data = GetLargeStringSpan();
for (int i = 0; i < 1000000; i++)
{
    var part = data.Slice(i, 10);
    Process(part);  // 0 allocations
}
// Execution time: 0.3 seconds, no GC during processing

📝 Span-Compatible APIs

// String extensions
ReadOnlySpan<char> text = "Hello World";
bool hasSpace = text.Contains(' ');
int index = text.IndexOf('W');

// Memory extensions
Memory<byte> memory = new byte[1024];
Span<byte> span = memory.Span;

// List to span (without copy)
List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
Span<int> spanFromList = CollectionsMarshal.AsSpan(numbers);

// String to span (no allocation)
ReadOnlySpan<char> spanFromString = "Hello";

// Utf8 parsing (high performance)
ReadOnlySpan<byte> utf8 = Encoding.UTF8.GetBytes("Hello");
var parsed = Encoding.UTF8.GetString(utf8);

💡 When to Use Span

  • High-frequency parsing (logs, CSV, JSON chunks)
  • Network packet processing
  • String manipulation in tight loops
  • Working with stackalloc for temporary buffers
  • Interop with native code (Span<T> pins memory automatically)
  • Don’t use: For long-lived storage (Span is ref-struct, can’t be field)

“Parsing 10GB log file. Substring allocated millions of strings → GC paused every second. Rewrote with ReadOnlySpan. Zero allocations. Processing time: 45 minutes → 4 minutes.”

— Performance Engineer

Related posts:

C#: Use default Literal for Cleaner Default Values

C#: Use default Literal for Cleaner Default Values

C#: LINQ Performance Tips to Avoid Common Pitfalls

C#: LINQ Performance Tips to Avoid Common Pitfalls

C#: Use Null-Coalescing Operator (??) for Defaults

C#: Use Null-Coalescing Operator (??) for Defaults

Views: 26
Found this useful? Share it
XLinkedInWhatsApp

Post navigation

SQL: Use Partial Indexes to Index Only Relevant Rows
C#: Use Native AOT to Compile .NET Apps to Single Executables

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Most Read

  1. 01How to make theater mode the default for Youtube 1,079 views
  2. 02How to add default value for Entity Framework migrations for DateTime and Bool 997 views
  3. 03Get the User Name and Domain Name from an Email Address in SQL 996 views
  4. 04Get the First and Last Word from a String or Sentence in SQL 873 views
  5. 05How to select distinct rows in a datatable in C# 868 views
  6. 06How to enable, disable and check if Service Broker is enabled on a database in SQL Server 671 views
  7. 07Add Constraint to SQL Table to ensure email contains @ 629 views
  8. 08Average of all values in a column that are not zero in SQL 584 views
  9. 09How to use Map Mode for Vertical Scroll Mode in Visual Studio 561 views
Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
Back to top
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com