Bad F# code performance on simple loop compared to C# - Why?

Viewed 858

I was wondering why I get such disparate results between apparently equal algorithms in C# and F#.

F# code variants:

open System
{ 1I..(bigint (Int32.MaxValue / 100)) } |> Seq.sum

let mutable sum = 0I
for i in 1I..(bigint (Int32.MaxValue / 100)) do
    sum <- sum + i
sum

let sum = ref 0I
for i in 1I..(bigint (Int32.MaxValue / 100)) do
    sum := !sum + i
sum

Full F# code (4s):

[<EntryPoint>]
let main argv = 
    let sw = new Stopwatch()
    sw.Start()
    printfn "%A" ({ 1I..(bigint (Int32.MaxValue / 100)) } |> Seq.sum)
    sw.Stop()
    printfn "took %A" sw.Elapsed
    Console.ReadKey() |> ignore
    0

Full C# code (22s):

static void Main(string[] args)
{
    Stopwatch sw = new Stopwatch();
    sw.Start();
    BigInteger sum = new BigInteger(0);
    BigInteger max = new BigInteger(Int32.MaxValue / 100);
    Console.WriteLine(max);
    for (BigInteger i = new BigInteger(1); i <= max; ++i)
    {
        sum += i;
    }
    sw.Stop();
    Console.WriteLine(sum);
    Console.WriteLine(sw.Elapsed);
    Console.ReadKey();
}

The F# code takes more than 22s on any of its variants (I assumed different implementations would yield different running times but that doesn't seem to be the case). On the other hand, the C# code seems to be way faster. Both yield the same final sum result, so I guess the algorithms are equivalent. I double checked and the F# code seems to be compiled with the --optimize+ flag.

Am I doing something wrong?

2 Answers
Related