System.OutOfMemoryException when generating permutations
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
System.OutOfMemoryException during permutation generation is usually not a runtime bug in .NET itself, but a design issue caused by factorial growth. Even moderate input sizes produce more permutations than memory can hold. This guide explains why it happens and how to redesign permutation code to be memory-safe.
Core Topic Sections
Understand the growth first
Number of permutations for n unique elements is n!. That growth is extreme:
10!equals 3,628,800.12!equals 479,001,600.15!exceeds one trillion.
If each permutation is stored as a new array, memory usage explodes quickly. The first fix is architectural: do not materialize everything unless input size is tiny.
Why list-based implementations fail
A common pattern builds a nested list structure and appends every permutation. This causes:
- Huge object allocation count.
- Frequent garbage collection pressure.
- Eventual memory exhaustion.
The correct model is stream processing. Generate one permutation, consume it, then move on.
Use iterator-based generation in C#
yield return allows lazy production of permutations.
This approach avoids a giant in-memory result list.
Consume permutations with pruning
Many real problems do not need all permutations. Stop early when a condition is met, or prune branches before full permutation completion.
Example strategy:
- Evaluate partial candidate cost.
- Abandon branch if cost already exceeds current best.
- Continue only promising branches.
Pruning transforms impossible workloads into practical ones.
Use counts and limits in API design
If this logic is exposed through a service or UI tool, enforce limits explicitly:
- Maximum input length.
- Maximum permutations processed.
- Timeout per request.
Fail fast with clear message if requested size is unsafe.
Parallelization does not solve memory design
Parallel generation can speed CPU work, but if each worker still stores large permutation sets, memory failures remain. Parallelism should combine with streaming and bounded queues.
Pattern:
- Producer generates permutations lazily.
- Worker pool consumes and scores.
- Results aggregator stores only best or top-N outcomes.
Bounded memory plus parallel compute is the sustainable model.
Diagnostics and measurement
Before optimization, instrument:
- Input size.
- Number of permutations processed.
- Peak memory.
- Time per million permutations.
Use these metrics to define practical limits and avoid repeating outages.
Alternative algorithms for specific goals
If your actual goal is not full enumeration, use specialized algorithms:
- For best route approximation, use heuristic search.
- For ranking top combinations, use branch-and-bound.
- For counting only, compute combinatorics directly without generation.
Choosing the right algorithm is often more impactful than low-level memory tuning.
Common Pitfalls
- Storing every permutation in nested lists before processing.
- Accepting large input sizes without guardrails or warning.
- Assuming more RAM will make factorial workloads safe.
- Adding parallel threads while keeping unbounded result accumulation.
- Ignoring pruning opportunities in optimization-style permutation tasks.
Summary
OutOfMemoryExceptionin permutation code is usually a factorial-growth design issue.- Avoid materializing full permutation sets for non-trivial input sizes.
- Use lazy iteration with
yield returnand process items incrementally. - Add limits, pruning, and observability for production safety.
- Prefer goal-specific algorithms when full permutation enumeration is unnecessary.
Related reading
- Table 'performance_schema.session_variables' doesn't exist
- TableView slow when adding images to cellForRowAtIndex
- Tail Recursion optimization for JavaScript?
- TargetedPatchingOptOut Performance critical to inline across NGen image boundaries?
- Tensor is not an element of this graph
- Tensor is not an element of this graph
- System.ServiceModel not found in .NET Core project
- System.Text.Json How do I specify a custom name for an enum value?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.