Skip to content

[API Proposal]: Analyzer - replace copy loop with span.CopyTo(destination) #99186

Open
@neon-sunset

Description

@neon-sunset

Background and motivation

Given copy unrolling improvements, using span.CopyTo(dest) should outperform manual copy with a loop in almost every situation. It may be desirable to have a performance analyzer rule to flag such use cases and suggest an auto-fixer to address them.

Example pattern spotted in

if (buffer.Length <= 4 && // Threshold of 4 chosen based on perf experimentation
buffer.Length <= _charLen - _charPos)
{
// For very short buffers and when we don't need to worry about running out of space
// in the char buffer, just copy the chars individually.
for (int i = 0; i < buffer.Length; i++)
{
_charBuffer[_charPos++] = buffer[i];
}

API Usage

var src = Enumerable
    .Range(0, 16)
    .Select(num => num.ToString())
    .ToArray()
    .AsSpan()
var dst = new string[16];

// Flagged with a rule "use span.CopyTo for copying elements"
for (var i = 0; i < src.Length; i++)
{
    dst[i] = src[i];
}

Alternative Designs

N/A

Risks

Should be none (right? :) )

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.Memorycode-analyzerMarks an issue that suggests a Roslyn analyzer

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions