为什么Seq.iter和Seq.map这么多慢?(why is Seq.iter and Seq.m

2019-06-25 03:25发布

考虑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!!!!

为什么itermap上的功能Seq模块比这么慢得多ArrayList模块等同?

Answer 1:

一旦你打电话进来Seq你失去了类型信息-移动到列表中的下一个元素,需要一个呼叫IEnumerator.MoveNext 。 比较为Array ,你只是增加一个索引和List你可以取消引用指针。 从本质上讲,你得到一个额外的函数调用列表中的每个元素。

该转换回到ListArray也有所下降出于同样的原因减缓码



文章来源: why is Seq.iter and Seq.map so much slower?