F#:为什么 Array.createZero 这么快? [英] F#: Why is Array.createZero so fast?
问题描述
我有这个代码:
let timer = new System.Diagnostics.Stopwatch()
timer.Start()
Array.zeroCreate<int> 100000000
timer.Stop()
printfn "%ims" timer.ElapsedMilliseconds
timer.Reset()
timer.Start()
Array.create 100000000 0
timer.Stop()
printfn "%ims" timer.ElapsedMilliseconds
我对其进行了测试,结果如下:
I tested it and had these results:
0ms
200ms
Array.zeroCreate
如何如此快速地创建数组并保证它的所有元素都有默认值?在其他语言中,我知道没有这样的可能性(据我所知).在其他语言中,我只知道数组的快速初始化,哪些元素不能保证具有默认值,因为它们可以在一些垃圾所在的内存中进行初始化.
How does Array.zeroCreate
create array so fast and it's guaranteed that all it's elements have default value? In other languages I know there are no such possibilities (as far as I know). In other languages I know only about fast initialization of array which elements are not guaranteed to have default value, because they can be initialized in memory where some garbage lies.
谢谢!
推荐答案
所以我们可以去查一下源码:
So we can just go and look up the source:
[<CompiledName("ZeroCreate")>]
let zeroCreate count =
if count < 0 then invalidArg "count" (SR.GetString(SR.inputMustBeNonNegative))
Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked count
和
[<CompiledName("Create")>]
let create (count:int) (x:'T) =
if count < 0 then invalidArg "count" (SR.GetString(SR.inputMustBeNonNegative))
let array = (Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked count : 'T[])
for i = 0 to Operators.Checked.(-) count 1 do // use checked arithmetic here to satisfy FxCop
array.[i] <- x
array
所以从这里我们可以看到 Create
做了更多的工作 - 所以它更慢.
so from this we can see that Create
does some more work - so it is slower.
我们可以更深入地找到底层函数:
We can go deeper and find the underlying function:
// The input parameter should be checked by callers if necessary
let inline zeroCreateUnchecked (count:int) =
(# "newarr !0" type ('T) count : 'T array #)
这基本上只是执行 CIL newarr
指令.
this basically just executes the CIL newarr
instruction.
可以通过调用具有适当大小的 calloc
来执行该指令,这会非常快.
This instruction could quite conceiveably be executed by calling calloc
with an appropriate size, which would be incredibly fast.
这篇关于F#:为什么 Array.createZero 这么快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!