<分区>
Possible Duplicate:
F# seems slower than other languages… what can I do to speed it up?
我对模式匹配的性能有点好奇,所以做了如下测试:
poolEven
包含 0,1,2,3 的 10000 个元素,(2500 等于)
testSize = 100000
IfelseEven(100000)
需要 650 毫秒(切换会更快,但我没有附上代码)而 MatchEven(100000)
需要 7000 毫秒,这是 10 倍的时间
性能下降是否来自 Array.Fold
?我 100% 确定,如果我选择 IEnumerable.Aggregate
,速度会大大降低。 但我认为 F# 处理 Array.Fold
的效果优于使用 IEnumerable.Aggregate
的 C#。我想比较两种语言中最常见(等效)编码方式的性能,而不是使它们相同的严格方式。
测试是在 x64 版本中完成的,10 次以上的试验在适当的预热下取平均值
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