Skip to content
This repository has been archived by the owner on Nov 1, 2020. It is now read-only.

Commit

Permalink
Use stackalloc in string.Split (dotnet/coreclr#15435)
Browse files Browse the repository at this point in the history
* 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
Alex authored and jkotas committed Feb 12, 2018
1 parent d99e21a commit 0ceefb1
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
<Compile Include="$(MSBuildThisFileDirectory)System\Collections\Generic\KeyNotFoundException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Collections\Generic\KeyValuePair.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Collections\Generic\NonRandomizedStringEqualityComparer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Collections\Generic\ValueListBuilder.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Collections\Generic\List.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Collections\HashHelpers.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Collections\ICollection.cs" />
Expand Down
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);
}
}
}
}

0 comments on commit 0ceefb1

Please sign in to comment.