考虑 F# 中的以下代码:
let n = 10000000
let arr = Array.init n (fun _ -> 0)
let rec buildList n acc i = if i = n then acc else buildList n (0::acc) (i + 1)
let lst = buildList n [] 0
let doNothing _ = ()
let incr x = x + 1
#time
arr |> Array.iter doNothing // this takes 14ms
arr |> Seq.iter doNothing // this takes 74ms
lst |> List.iter doNothing // this takes 19ms
lst |> Seq.iter doNothing // this takes 88ms
arr |> Array.map incr // this takes 33ms
arr |> Seq.map incr |> Seq.toArray // this takes 231ms!
lst |> List.map incr // this takes 753ms
lst |> Seq.map incr |> Seq.toList // this takes 2111ms!!!!
为什么是iter
and map
上的函数Seq
模块比Array
and List
模块等效项?
一旦您致电Seq
您丢失了类型信息 - 移动到列表中的下一个元素需要调用IEnumerator.MoveNext
。比较对于Array
你只需增加一个索引并为List
你可以只取消引用一个指针。本质上,您会为列表中的每个元素进行额外的函数调用。
转换回List
and Array
由于类似的原因也会减慢代码速度
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)