This repository has been archived by the owner on Nov 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 508
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Use stackalloc in string.Split (dotnet/coreclr#15435)
* Use stackalloc in string.Split * Added initial usage of ValueListBuilder * Added usage of list builder to string separator Split overloads Signed-off-by: dotnet-bot <[email protected]>
- Loading branch information
Showing
2 changed files
with
68 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
67 changes: 67 additions & 0 deletions
67
src/System.Private.CoreLib/shared/System/Collections/Generic/ValueListBuilder.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
// See the LICENSE file in the project root for more information. | ||
|
||
using System.Buffers; | ||
using System.Diagnostics; | ||
using System.Runtime.CompilerServices; | ||
|
||
namespace System.Collections.Generic | ||
{ | ||
internal ref struct ValueListBuilder<T> | ||
{ | ||
private Span<T> _span; | ||
private T[] _arrayFromPool; | ||
private int _pos; | ||
|
||
public ValueListBuilder(Span<T> initialSpan) | ||
{ | ||
_span = initialSpan; | ||
_arrayFromPool = null; | ||
_pos = 0; | ||
} | ||
|
||
public int Length => _pos; | ||
|
||
[MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
public void Append(T item) | ||
{ | ||
int pos = _pos; | ||
if (pos >= _span.Length) | ||
Grow(); | ||
|
||
_span[pos] = item; | ||
_pos = pos + 1; | ||
} | ||
|
||
public ReadOnlySpan<T> AsReadOnlySpan() | ||
{ | ||
return _span.Slice(0, _pos); | ||
} | ||
|
||
[MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
public void Dispose() | ||
{ | ||
if (_arrayFromPool != null) | ||
{ | ||
ArrayPool<T>.Shared.Return(_arrayFromPool); | ||
_arrayFromPool = null; | ||
} | ||
} | ||
|
||
private void Grow() | ||
{ | ||
T[] array = ArrayPool<T>.Shared.Rent(_span.Length * 2); | ||
|
||
bool success = _span.TryCopyTo(array); | ||
Debug.Assert(success); | ||
|
||
T[] toReturn = _arrayFromPool; | ||
_span = _arrayFromPool = array; | ||
if (toReturn != null) | ||
{ | ||
ArrayPool<T>.Shared.Return(toReturn); | ||
} | ||
} | ||
} | ||
} |