Skip to content

Commit 54fd4d1

Browse files
committedMar 25, 2023
ArraySegment
1 parent e95afee commit 54fd4d1

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
 

‎docs/collections.md

+28
Original file line numberDiff line numberDiff line change
@@ -289,3 +289,31 @@ Result:
289289
| InterSectionList | 25.69 us | 0.416 us | 0.369 us | 1.00 |
290290
| InterSectionHashSet | 11.88 us | 0.108 us | 0.090 us | 0.46 |
291291
```
292+
293+
## Use `ArraySegment<T>` for efficient slicing of arrays
294+
When slicing an array a new array is created. This is especially expensive when the array is large. `ArraySegment<T>` is a struct that holds a reference to the original array and the start and end index of the slice. This is much more efficient than creating a new one. Be aware that the `ArraySegment<T>` is a read-only view of the original array and any changes to the original array will be reflected in the `ArraySegment<T>`.
295+
296+
**Bad** We create a new array when taking a slice of the original array, leading to extra memory allocations.
297+
```csharp
298+
299+
public int[] Slice(int[] array, int offset, int count)
300+
{
301+
var result = new int[count];
302+
Array.Copy(array, offset, result, 0, count);
303+
return result;
304+
}
305+
306+
var originalArray = new int[] { 1, 2, 3, 4, 5 };
307+
var slicedArray = Slice(originalArray, 1, 3); // Creates a new array { 2, 3, 4 }
308+
```
309+
310+
**Good** Use `ArraySegment<T>` to create a view of the original array without creating a new array, avoiding the extra memory allocation.
311+
```csharp
312+
public ArraySegment<int> Slice(int[] array, int offset, int count)
313+
{
314+
return new ArraySegment<int>(array, offset, count);
315+
}
316+
317+
var originalArray = new int[] { 1, 2, 3, 4, 5 };
318+
var slicedArray = Slice(originalArray, 1, 3); // A view over { 2, 3, 4 } in the original array
319+
```

0 commit comments

Comments
 (0)