Levenshtein Distance 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 your String Algorithms question into a ready to paste AI prompt, free →
Key Takeaways
- ✓Levenshtein Distance runs in O(n*m) time and O(n*m) space, in C# as in every other language.
- ✓The BCL has no edit distance; System.String offers comparison, not distance. On NuGet the practical picks are Quickenshtein (Levenshtein.GetDistance(a, b), vectorised with System.Numerics.Vector) and FuzzySharp for the whole ratio family.
- ✓Reviewers want ReadOnlySpan<char> parameters rather than string, so a caller can pass a slice without allocating a substring; the method then cannot be async, and that trade is accepted here.
- ✓The C# trap: The obvious int[,] dp = new int[n + 1, m + 1] is the shape to avoid. A rectangular multidimensional array gets weaker JIT codegen than a jagged int[][] or a Span<int>, because the index arithmetic and its bounds checks are not the single-dimension pattern the JIT folds, and there is no Span<T> constructor that wraps a T[,], so the fast path is unavailable without unsafe tricks.
- ✓Two stackalloc'd Span<int> rows keep the working set inside a couple of cache lines and cost nothing to release; ArrayPool<int>.Shared covers the long case without adding GC pressure.
What Levenshtein Distance actually is
Levenshtein Distance in C#: what you actually reach for
C# implementation
using System;
using System.Buffers;
public static class Levenshtein
{
public static int Distance(ReadOnlySpan<char> a, ReadOnlySpan<char> b)
{
if (a.Length < b.Length) { var t = a; a = b; b = t; }
if (b.IsEmpty) return a.Length;
int width = b.Length + 1;
int[]? rented = width > 256 ? ArrayPool<int>.Shared.Rent(width * 2) : null;
// Allocated ONCE, above the loops. stackalloc inside a loop never unwinds.
Span<int> prev = rented is null ? stackalloc int[width] : rented.AsSpan(0, width);
Span<int> cur = rented is null ? stackalloc int[width] : rented.AsSpan(width, width);
try
{
for (int j = 0; j < width; j++) prev[j] = j;
for (int i = 1; i <= a.Length; i++)
{
cur[0] = i;
char ai = a[i - 1];
for (int j = 1; j < width; j++)
{
int sub = prev[j - 1] + (ai == b[j - 1] ? 0 : 1);
cur[j] = Math.Min(sub, Math.Min(prev[j] + 1, cur[j - 1] + 1));
}
var tmp = prev; prev = cur; cur = tmp;
}
return prev[b.Length];
}
finally
{
if (rented is not null) ArrayPool<int>.Shared.Return(rented);
}
}
}
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*m)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Levenshtein Distance?
The BCL has no edit distance; System.String offers comparison, not distance. On NuGet the practical picks are Quickenshtein (Levenshtein.GetDistance(a, b), vectorised with System.Numerics.Vector) and FuzzySharp for the whole ratio family. What the BCL does give you is the machinery: Span<int> and stackalloc for the rows, ArrayPool<int>.Shared for long inputs, System.Text.Rune plus MemoryExtensions.EnumerateRunes over s.AsSpan() for code-point iteration, StringInfo in System.Globalization for text elements, and string.Normalize(NormalizationForm.FormC).
What is the most common C# mistake when implementing Levenshtein Distance?
The obvious int[,] dp = new int[n + 1, m + 1] is the shape to avoid. A rectangular multidimensional array gets weaker JIT codegen than a jagged int[][] or a Span<int>, because the index arithmetic and its bounds checks are not the single-dimension pattern the JIT folds, and there is no Span<T> constructor that wraps a T[,], so the fast path is unavailable without unsafe tricks. The second trap is stackalloc inside the outer loop: the stack frame is only unwound when the method returns, so each iteration piles on another buffer and a long input dies with a StackOverflowException that no catch block can handle. Allocate both rows once, above the loops.
How does Levenshtein Distance actually perform in C#?
Two stackalloc'd Span<int> rows keep the working set inside a couple of cache lines and cost nothing to release; ArrayPool<int>.Shared covers the long case without adding GC pressure. Bounds checks vanish only when the JIT can see the loop bound come from the span being indexed, so write for (int j = 0; j < prev.Length; j++) and for (int j = 1; j < cur.Length; j++) rather than bounding on the width local, which is a copy it cannot prove equal; keep width for the stackalloc-versus-rent sizing decision only. Tiered compilation runs the first calls as unoptimised tier-0 code, so measure only after warm-up. char is 16 bits but the rows are int: a 1,000-character input needs 4 KB per row, which is what decides your stackalloc threshold. Time complexity is O(n*m) and space is O(n*m).
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 trialBefore paying full price for a tool, check the student deals on AI and developer tools listed 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.