the*_*onk 11 performance f# seq
在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!!!!
Run Code Online (Sandbox Code Playgroud)
为什么iter
和map
功能上的Seq
模块比这么慢得多Array
和List
模块等同?
Joh*_*mer 13
一旦你打电话给Seq
你丢失类型信息 - 移动到列表中的下一个元素需要调用IEnumerator.MoveNext
.比较Array
你只是增加一个索引,List
你可以只取消引用一个指针.实际上,您正在为列表中的每个元素获取额外的函数调用.
由于类似的原因,转换回来List
并Array
减慢代码速度