【发布时间】:2011-08-31 13:05:35
【问题描述】:
C# 和 F# 中的 Levenshtein 实现。对于大约 1500 个字符的两个字符串,C# 版本的速度提高了 10 倍。 C#:69 毫秒,F# 867 毫秒。为什么?据我所知,他们做同样的事情?不管是发布版本还是调试版本。
编辑:如果有人专门来这里寻找“编辑距离”实现,那它就坏了。工作代码是here。
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]
【问题讨论】:
-
使用内联的性能差异是多少?
标签: c# performance f# inline