11

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モジュールのandmap関数が同等のandモジュールSeqよりもずっと遅いのはなぜですか?ArrayList

4

1 に答える 1

14

を呼び出すとSeq、タイプ情報が失われます。リスト内の次の要素に移動するには、を呼び出す必要がありますIEnumerator.MoveNextArrayインデックスをインクリメントするだけListで、ポインターを逆参照できるだけです。基本的に、リスト内の各要素に対して追加の関数呼び出しを取得しています。

同様の理由で、変換が元に戻りListArrayコードが遅くなります

于 2012-06-03T23:25:47.800 に答える