Skip to content

Use safe Span.Slice loop pattern in Enumerable.FillIncrementing#127427

Merged
EgorBo merged 1 commit intodotnet:mainfrom
EgorBo:copilot/safe-loop-range
Apr 26, 2026
Merged

Use safe Span.Slice loop pattern in Enumerable.FillIncrementing#127427
EgorBo merged 1 commit intodotnet:mainfrom
EgorBo:copilot/safe-loop-range

Conversation

@EgorBo
Copy link
Copy Markdown
Member

@EgorBo EgorBo commented Apr 25, 2026

Note

This PR was authored with assistance from GitHub Copilot (AI-generated content).

Rewrites the vectorized fill in Enumerable.FillIncrementing<T> to use the safe while (span.Length >= CONST) { ...; span = span.Slice(CONST); } loop pattern, removing all Unsafe.* / MemoryMarshal.GetReference plumbing. JIT recognizes this shape and elides the bounds checks.

Codegen

Small diffs, no new checks. No perf impact.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot AI review requested due to automatic review settings April 25, 2026 17:35
@EgorBo
Copy link
Copy Markdown
Member Author

EgorBo commented Apr 25, 2026

@MihuBot

@dotnet-policy-service
Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-linq
See info in area-owners.md if you want to be subscribed.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Refactors Enumerable.FillIncrementing<T> to use a safe Span<T>.Slice-driven loop shape for the vectorized fill, eliminating Unsafe/MemoryMarshal usage while keeping JIT-friendly bounds-check elimination.

Changes:

  • Removed Unsafe.* / MemoryMarshal.GetReference pointer-walking in FillIncrementing<T>.
  • Replaced vector stores with Vector<T>.CopyTo(destination) inside a while (destination.Length >= Vector<T>.Count) loop and advanced via destination = destination.Slice(...).
  • Simplified the scalar tail fill to iterate directly over the remaining span.

@EgorBo
Copy link
Copy Markdown
Member Author

EgorBo commented Apr 25, 2026

@EgorBot -intel -arm

using System.Linq;
using BenchmarkDotNet.Attributes;

public class RangeToArrayBench
{
    [Params(0, 1, 4, 8, 16, 64, 256, 1024, 16384, 1_000_000)]
    public int Count;

    [Benchmark]
    public int[] RangeToArray() => Enumerable.Range(0, Count).ToArray();
}

@EgorBo EgorBo marked this pull request as ready for review April 25, 2026 19:28
@EgorBo EgorBo merged commit 4e26169 into dotnet:main Apr 26, 2026
102 of 106 checks passed
@EgorBo EgorBo deleted the copilot/safe-loop-range branch April 26, 2026 11:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants