[英]Why is this F# code so slow?
C# 和 F# 中的 Levenshtein 实现。 C# 版本对于两个大约 1500 个字符的字符串要快 10 倍。 C#:69 毫秒,F# 867 毫秒。 为什么? 据我所知,他们做同样的事情? 不管是发布版本还是调试版本。
编辑:如果有人来这里专门寻找“编辑距离”实现,它就坏了。 工作代码在这里。
C# :
private static int min3(int a, int b, int c)
{
return Math.Min(Math.Min(a, b), c);
}
public static int EditDistance(string m, string n)
{
var d1 = new int[n.Length];
for (int x = 0; x < d1.Length; x++) d1[x] = x;
var d0 = new int[n.Length];
for(int i = 1; i < m.Length; i++)
{
d0[0] = i;
var ui = m[i];
for (int j = 1; j < n.Length; j++ )
{
d0[j] = 1 + min3(d1[j], d0[j - 1], d1[j - 1] + (ui == n[j] ? -1 : 0));
}
Array.Copy(d0, d1, d1.Length);
}
return d0[n.Length - 1];
}
F# :
let min3(a, b, c) = min a (min b c)
let levenshtein (m:string) (n:string) =
let d1 = Array.init n.Length id
let d0 = Array.create n.Length 0
for i=1 to m.Length-1 do
d0.[0] <- i
let ui = m.[i]
for j=1 to n.Length-1 do
d0.[j] <- 1 + min3(d1.[j], d0.[j-1], d1.[j-1] + if ui = n.[j] then -1 else 0)
Array.blit d0 0 d1 0 n.Length
d0.[n.Length-1]
The problem is that the min3
function is compiled as a generic function that uses generic comparison (I thought this uses just IComparable
, but it is actually more complicated - it would use structural comparison for F# types and it's fairly complex logic).
> let min3(a, b, c) = min a (min b c);;
val min3 : 'a * 'a * 'a -> 'a when 'a : comparison
在 C# 版本中, function 不是通用的(它只需要int
)。 您可以通过添加类型注释来改进 F# 版本(以获得与 C# 中相同的内容):
let min3(a:int, b, c) = min a (min b c)
...或通过将min3
设为inline
(在这种情况下,使用时它将专门用于int
):
let inline min3(a, b, c) = min a (min b c);;
对于长度为 300 的随机字符串str
,我得到以下数字:
> levenshtein str ("foo" + str);;
Real: 00:00:03.938, CPU: 00:00:03.900, GC gen0: 275, gen1: 1, gen2: 0
val it : int = 3
> levenshtein_inlined str ("foo" + str);;
Real: 00:00:00.068, CPU: 00:00:00.078, GC gen0: 0, gen1: 0, gen2: 0
val it : int = 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.