对于下面的示例,我很惊讶 List 范围有多慢。在我的机器上,for 循环要快 8 倍左右。
是否首先创建了 10,000,000 个元素的实际列表?如果是这样,是否有原因(除了尚未完成)为什么编译器无法优化它?
open System
open System.Diagnostics
let timeFunction f v =
let sw = Stopwatch.StartNew()
let result = f v
sw.ElapsedMilliseconds
let length = 10000000
let doSomething n =
(float n) ** 0.1 |> ignore
let listIter n =
[1..length] |> List.iter (fun x -> doSomething (x+n))
let forLoop n =
for x = 1 to length do
doSomething (x+n)
printf "listIter : %d\n" (timeFunction listIter 1) // c50
GC.Collect()
printf "forLoop : %d\n" (timeFunction forLoop 1) // c1000
GC.Collect()