Generic function significantly slower than function with specific type #17042
-
A C# vs F# performance question was asked on the fsharp.org forums and I was able to solve the issue, but I am not sure what's going on. It would appear that a generic function is significantly slower than a type specified one. I'm reposing this here to hopefully get some more visibility because this seems like unexpected behavior. The post in question: F# vs C# performance Copy of altbodhi's Original post:
let inline swap<'a> (a: byref<'a>, b: byref<'a>) =
let t = a
a <- b
b <- t
let sort arr =
let ln = Array.length arr
for i = 0 to ln - 1 do
for j = 0 to ln - 2 - i do
if arr.[j + 1] < arr.[j] then
swap (&arr.[j + 1], &arr.[j])
let doTest () =
let max = 100_000
let value = float (max)
let arr =
Array.init max (fun i -> value - float (i))
sort arr
printfn "%A" (arr.[0..5])
#time
doTest ()
using System.Runtime.CompilerServices;
var m = 100_000;
var a = new double[m];
var s = (double)m;
for (var i = 0; i < m; i++)
{
a[i] = s;
s = s - 1;
}
Sort(a);
Console.WriteLine(a[0]);
static void Sort(double[] a)
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void Swap(ref double x, ref double y)
{
var t = x;
x = y;
y = t;
}; My original response:
let sort arr =
let sort (arr: float array) =
I’m on an M1 Mac with .NET 7.0.100. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
TL;DR it's likely because of how comparison works in F# (due to Generic comparison will be involved (like |
Beta Was this translation helpful? Give feedback.
TL;DR it's likely because of how comparison works in F# (due to
comparison
constraint).Generic comparison will be involved (like
GenericLessThanIntrinsic
, since function is, well, generic), which is not inlined as far as I remember as well as has some logic in it to chose specific implementation.