Skip to content

Commit

Permalink
reverse-string: fix span approach code
Browse files Browse the repository at this point in the history
  • Loading branch information
ErikSchierboom committed Sep 29, 2023
1 parent 60212a7 commit f1b2731
Showing 1 changed file with 14 additions and 6 deletions.
20 changes: 14 additions & 6 deletions exercises/practice/reverse-string/.approaches/span/content.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
# Span<T>

```csharp
Span<char> chars = stackalloc[input.Length];
for (var i = 0; i < input.Length; i++)
public static class ReverseString
{
chars[input.Length - 1 - i] = input[i];
public static string Reverse(string input)
{
Span<char> chars = stackalloc[input.Length];

for (var i = 0; i < input.Length; i++)
{
chars[input.Length - 1 - i] = input[i];
}

return new string(chars);
}
}
return new string(chars);
```

C# 7.2. introduced the [`Span<T>`][span-t] class, which was specifically designed to allow performant iteration/mutation of _array-like_ objects.
Expand Down Expand Up @@ -39,10 +47,10 @@ Span<char> chars = stackalloc char[input.Length];

With this version, the memory allocated for the `Span<char>` is all on the stack and no garbage collection is needed for that data.

~~~~exercism/caution
```exercism/caution
The stack has a finite amount of memory.
This means that for large strings, the above code will result in a `StackOverflowException` being thrown.
~~~~
```

So what is the limit for the amount of memory we can allocate?
Well, this depends on how memory has already been allocated on the stack.
Expand Down

0 comments on commit f1b2731

Please sign in to comment.