当我将列表转换为其他集合类型时,是否有理由更喜欢ofList
函数而不是ofSeq
?
答案 0 :(得分:3)
每种方法之间可能存在性能差异,您通常会期望更专业的转换可以提供更好的结果。
举一个例子,Array.ofList
是通过此功能(https://github.com/fsharp/fsharp/blob/37a100b7caafde0f4df5a1924c9f65f4a18277a8/src/fsharp/FSharp.Core/local.fs#L300)实现的:
let toArray (l:'T list) =
let len = l.Length
let res = arrayZeroCreate len
let rec loop i l =
match l with
| [] -> ()
| h::t ->
res.[i] <- h
loop (i+1) t
loop 0 l
res
虽然Array.ofSeq
通过Seq.toArray
(https://github.com/fsharp/fsharp/blob/master/src/fsharp/FSharp.Core/seq.fs#L1231):
let toArray (source : seq<'T>) =
checkNonNull "source" source
match source with
| :? ('T[]) as res -> (res.Clone() :?> 'T[])
| :? ('T list) as res -> List.toArray res
| :? ICollection<'T> as res ->
// Directly create an array and copy ourselves.
// This avoids an extra copy if using ResizeArray in fallback below.
let arr = Array.zeroCreateUnchecked res.Count
res.CopyTo(arr, 0)
arr
| _ ->
let res = ResizeArray<_>(source)
res.ToArray()
请注意,在这种情况下,ofSeq
函数实际上会检查所提供的序列是否为list
,如果是,则使用专门的转换。