Run-Length Encoding Implementation in C#
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Run-Length Encoding runs in O(n) time and O(n) space, in C# as in every other language.
- ✓System.Text.StringBuilder is the accumulator, and its Append(char value, int repeatCount) overload is exactly a decoded run in one call.
- ✓Reviewers want ReadOnlySpan<char> on the read side and StringBuilder or string.Create on the write side, never s += part.
- ✓The C# trap: Span<char> and ReadOnlySpan<char> are ref structs: stack-only, so they cannot be a field of a class, cannot survive an await, and cannot exist inside an iterator method.
- ✓StringBuilder is a linked list of char chunks, so growth never re-copies what is already written, but ToString() must walk every chunk and copy into one final array; for a known output length string.Create skips that second pass entirely.
What Run-Length Encoding actually is
Run-Length Encoding in C#: what you actually reach for
C# implementation
using System;
using System.Text;
public static class Rle
{
/// <summary>Run-length encodes s, counting UTF-16 code units.</summary>
public static string Encode(ReadOnlySpan<char> s)
{
var sb = new StringBuilder(s.Length);
int i = 0;
while (i < s.Length)
{
char c = s[i];
int n = 1;
while (i + n < s.Length && s[i + n] == c) n++;
sb.Append(c);
if (n > 1) sb.Append(n); // formats in place, no ToString()
i += n;
}
return sb.ToString();
}
public static string Decode(ReadOnlySpan<char> s)
{
var sb = new StringBuilder(s.Length * 2);
int i = 0;
while (i < s.Length)
{
char c = s[i++];
int n = 0;
while (i < s.Length && s[i] is >= '0' and <= '9')
n = n * 10 + (s[i++] - '0');
sb.Append(c, n == 0 ? 1 : n);
}
return sb.ToString();
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe C#-specific trap
Performance in C#, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Run-Length Encoding?
System.Text.StringBuilder is the accumulator, and its Append(char value, int repeatCount) overload is exactly a decoded run in one call. ReadOnlySpan<char> from System lets the encoder read a slice of the input with no allocation. System.Text.Rune models a full Unicode scalar, and string.EnumerateRunes() returns a StringRuneEnumerator over them; that is what you want instead of foreach (char c in s), which walks UTF-16 units. string.Create<TState>(int length, TState state, SpanAction<char, TState> action) writes the final string in place when the output length is known up front.
What is the most common C# mistake when implementing Run-Length Encoding?
Span<char> and ReadOnlySpan<char> are ref structs: stack-only, so they cannot be a field of a class, cannot survive an await, and cannot exist inside an iterator method. The obvious streaming API (static IEnumerable<(char Ch, int Count)> Runs(ReadOnlySpan<char> s) with yield return) simply does not compile, and the compiler error points at the iterator rather than at the span. You either materialise a List<(char, int)> and surrender the whole allocation win, or hand-write a ref struct enumerator exposing GetEnumerator, MoveNext and Current for foreach to duck-type onto.
How does Run-Length Encoding actually perform in C#?
StringBuilder is a linked list of char chunks, so growth never re-copies what is already written, but ToString() must walk every chunk and copy into one final array; for a known output length string.Create skips that second pass entirely. Append(int) formats through int.TryFormat straight into the chunk's span. The JIT hoists the bounds check on s[i] for a canonical for (i = 0; i < s.Length; i++) but usually not for an i + n < s.Length probe; the Encode above is written with exactly that probe for compactness, so its inner scan keeps its bounds check, and a monotone cursor (int j = i + 1; while (j < s.Length && s[j] == c) j++; int n = j - i;) is the shape that lets the check hoist. Spans behave the same. Tiered compilation runs the first thousands of iterations unoptimised until on-stack replacement kicks in. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what GitHub Copilot offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.