Possible Duplicate:
F# seems slower than other languages… what can I do to speed it up?
I am a bit curious about the performance of pattern match, so I did the following test:
poolEven
contains 10000 elements of 0,1,2,3, (2500 equal)
testSize = 100000
IfelseEven(100000)
takes 650ms (switch would be faster but I didn't attach the code) while MatchEven(100000)
takes 7000ms that's 10x time
Does the performance degradation come from Array.Fold
? I am 100% sure that if I go for IEnumerable.Aggregate
the speed would greatly decrease. But I thought F# handled Array.Fold
better than C# with IEnumerable.Aggregate
. I want to compare performance of most common (equivalent) ways of coding in 2 languages but not rigid ways to make them identical.
The tests are done in x64 release, with 10+ trials taken average with proper warm up
C#:
public void IfelseEven(int testSize)
{
Ifelse(testSize, poolEven);
}
void Ifelse(int testSize, int[] pool)
{
long sum = 0;
for (int i = 0; i < testSize; i++)
{
for (int j = 0; j < poolCapacity;j++ )
{
var item = pool[j];
if (item == 0)
{
sum += 5;
}
else if (item == 1)
{
sum += 1;
}
else if (item == 2)
{
sum += 2;
}
else if (item == 3)
{
sum += 3;
}
else
{
sum += 4;
}
}
}
}
public void MatchEven(int testSize)
{
PatternMatch.myMatch(testSize, poolEven);
}
F#:
module PatternMatch
let mat acc elem =
acc +
match elem with
| 0 -> 5L
| 1 -> 1L
| 2 -> 2L
| 3 -> 3L
| _ -> 4L
let sum (pool:int[])=
Array.fold mat 0L pool;
let myMatch testSize pool=
let mutable tmp = 0L
for i=0 to testSize do
tmp <- sum(pool) + tmp
tmp