Skip to content

Instantly share code, notes, and snippets.

@ufcpp
Created January 30, 2022 05:23

Revisions

  1. ufcpp created this gist Jan 30, 2022.
    40 changes: 40 additions & 0 deletions SpanBenchmark.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    using BenchmarkDotNet.Attributes;
    using BenchmarkDotNet.Running;

    BenchmarkRunner.Run<SpanBenchmark>();

    [MemoryDiagnoser]
    public class SpanBenchmark
    {
    private const int N = 1000;

    [Benchmark]
    public void IntArray()
    {
    for (int i = 0; i < N; i++)
    {
    m(i);
    }

    static int m(int i)
    {
    ReadOnlySpan<int> table = new[] { 1, 0, -1, 0 }; // 差はこの行だけ
    return table[i % 4];
    }
    }

    [Benchmark]
    public void SByteArray()
    {
    for (int i = 0; i < N; i++)
    {
    m(i);
    }

    static int m(int i)
    {
    ReadOnlySpan<sbyte> table = new sbyte[] { 1, 0, -1, 0 }; // 差はこの行だけ
    return table[i % 4];
    }
    }
    }