File tree Expand file tree Collapse file tree 1 file changed +14
-6
lines changed
exercises/practice/reverse-string/.approaches/span Expand file tree Collapse file tree 1 file changed +14
-6
lines changed Original file line number Diff line number Diff line change 1
1
# Span< ; T> ;
2
2
3
3
``` csharp
4
- Span < char > chars = stackalloc [input .Length ];
5
- for (var i = 0 ; i < input .Length ; i ++ )
4
+ public static class ReverseString
6
5
{
7
- chars [input .Length - 1 - i ] = input [i ];
6
+ public static string Reverse (string input )
7
+ {
8
+ Span < char > chars = stackalloc [input .Length ];
9
+
10
+ for (var i = 0 ; i < input .Length ; i ++ )
11
+ {
12
+ chars [input .Length - 1 - i ] = input [i ];
13
+ }
14
+
15
+ return new string (chars );
16
+ }
8
17
}
9
- return new string (chars );
10
18
```
11
19
12
20
C# 7.2. introduced the [ ` Span<T> ` ] [ span-t ] class, which was specifically designed to allow performant iteration/mutation of _ array-like_ objects.
@@ -39,10 +47,10 @@ Span<char> chars = stackalloc char[input.Length];
39
47
40
48
With this version, the memory allocated for the ` Span<char> ` is all on the stack and no garbage collection is needed for that data.
41
49
42
- ~~~~ exercism/caution
50
+ ``` exercism/caution
43
51
The stack has a finite amount of memory.
44
52
This means that for large strings, the above code will result in a `StackOverflowException` being thrown.
45
- ~~~~
53
+ ```
46
54
47
55
So what is the limit for the amount of memory we can allocate?
48
56
Well, this depends on how memory has already been allocated on the stack.
You can’t perform that action at this time.
0 commit comments