Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: Use Span CopyTo instead of Array CopyTo for better performance #13132

Merged
merged 1 commit into from
Aug 6, 2023

Conversation

Youssef1313
Copy link
Member

Benchmark:

    private static object UnsetValue = new();

    private static object[] _unsetStack = new object[10] { UnsetValue, UnsetValue, UnsetValue, UnsetValue, UnsetValue, UnsetValue, UnsetValue, UnsetValue, UnsetValue, UnsetValue };

    [Benchmark(Baseline = true)]
    public void ArrayCopy()
    {
        var arr = new object[10];
        Array.Copy(_unsetStack, arr, 10);
    }

    [Benchmark]
    public void SpanCopyToSpan()
    {
        var arr = new object[10];
        MemoryMarshal.CreateSpan(ref MemoryMarshal.GetArrayDataReference(_unsetStack), 10).CopyTo(MemoryMarshal.CreateSpan(ref MemoryMarshal.GetArrayDataReference(arr), 10));
    }

    [Benchmark]
    public void ArrayFill()
    {
        var arr = new object[10];
        Array.Fill(arr, UnsetValue);
    }

Outcome:

Method Mean Error StdDev Ratio RatioSD Gen 0 Gen 1 Gen 2 Allocated
ArrayCopy 14.60 ns 0.115 ns 0.096 ns 1.00 0.00 0.0497 - - 104 B
SpanCopyToSpan 10.68 ns 0.071 ns 0.063 ns 0.73 0.00 0.0497 - - 104 B
ArrayFill 30.13 ns 0.355 ns 0.332 ns 2.06 0.02 0.0497 - - 104 B

@MartinZikmund MartinZikmund merged commit a1f8b34 into unoplatform:master Aug 6, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants