hardConceptCodingSeniorStaff
A hot path allocates heavily and garbage collection is showing up in your profile. What does Span give you that a substring does not?
4 min readUpdated 2026-08-15
Answer
Short answer
Span is a stack-only view over memory you already have, so slicing it costs nothing while Substring allocates a new string and copies.It removes allocations rather than making them faster, which is the right lever in a runtime where the cost is collection pressure rather than the allocation itself.
Was this answer helpful?
Likely follow-ups
- Why can a Span not be used in an async method?
- When would you reach for Memory instead, and what does it cost?
- What is the large object heap and when does it start mattering here?
- How would you prove this change was worth making?
Related questions
- How does the .NET garbage collector decide what to collect, and how would you make a hot path allocate less?hardAlso on garbage-collection and memory6 min
- What happens when you append to a slice, and when do two slices stop sharing memory?mediumAlso on memory and garbage-collection5 min
- Memory keeps climbing in a Go service under load. How do you find out why, and what can you actually tune?hardAlso on garbage-collection and memory6 min
- A long-running Python service keeps climbing in memory and never comes back down. How do you work out where the memory went?hardAlso on memory and garbage-collection5 min