gpt4 book ai didi

c# - 为什么这个 F# 代码这么慢?

转载 作者:行者123 更新时间:2023-12-03 17:40:49 24 4
gpt4 key购买 nike

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]

最佳答案

问题在于min3函数被编译为使用泛型比较的泛型函数(我认为这仅使用 IComparable ,但它实际上更复杂 - 它会使用 F# 类型的结构比较,并且它是相当复杂的逻辑)。

> let min3(a, b, c) = min a (min b c);;
val min3 : 'a * 'a * 'a -> 'a when 'a : comparison

在 C# 版本中,该函数不是通用的(它只需要 int )。您可以通过添加类型注释来改进 F# 版本(以获得与 C# 相同的内容):

let min3(a:int, b, c) = min a (min b c)

...或通过制作 min3inline (在这种情况下,使用时将专门用于 int):

let inline min3(a, b, c) = min a (min b c);;

对于随机字符串 str长度为 300,我得到以下数字:

> 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

关于c# - 为什么这个 F# 代码这么慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36710722/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com