fsharp icon indicating copy to clipboard operation
fsharp copied to clipboard

Array slicing should be delegated to the BCL

Open kerams opened this issue 8 months ago • 0 comments

Instead of emitting significantly slower code similar to

int num = a.Length;
int num2 = ((5 >= 0 + num) ? (0 + num - 1) : 5);
int num3 = num2 - 1 + 1;
int num4 = ((num3 >= 0) ? num3 : 0);
byte[] array = new byte[num4];
int num5 = 0;
int num6 = num4 - 1;
if (num6 >= num5)
{
    while (true)
    {
        array[num5] = a[1 + num5];
        num5++;
        if (num5 == num6 + 1)
        {
            break;
        }
    }
}
return array;

Bench

[<MemoryDiagnoser; ShortRunJob>]
type Benchmarks () =
    let b = [| for _ in 1 .. 100_000 -> byte DateTime.Now.Ticks |]

    [<Benchmark>]
    member _.x () =
        b.[ 20 .. 4999 ]

    [<Benchmark>]
    member f.xx () =
        let out = GC.AllocateUninitializedArray<byte> (4980, false)
        Array.Copy (b, 20, out, 0, 4980)
        out

    [<Benchmark>]
    member gg.xxx () =
        b.AsSpan(20, 4980).ToArray ()
BenchmarkDotNet v0.14.0, Windows 11 (10.0.26100.4061)
AMD Ryzen 9 7900, 1 CPU, 24 logical and 12 physical cores
.NET SDK 10.0.100-preview.4.25258.110
  [Host]   : .NET 10.0.0 (10.0.25.25910), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI DEBUG
  ShortRun : .NET 10.0.0 (10.0.25.25910), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI

Job=ShortRun  IterationCount=3  LaunchCount=1
WarmupCount=3
Method Mean Error StdDev Gen0 Allocated
x 1,600.1 ns 316.27 ns 17.34 ns 0.2975 4.89 KB
xx 100.9 ns 90.66 ns 4.97 ns 0.2984 4.89 KB
xxx 117.1 ns 93.10 ns 5.10 ns 0.2992 4.89 KB

kerams avatar Jun 01 '25 09:06 kerams