我有这样的code:
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所以从这个可以看出,创建做一些更多的工作 - 所以它是慢
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.
该指令可以很conceiveably通过调用释放calloc 具有适当的大小,这将是令人难以置信的快速执行。
This instruction could quite conceiveably be executed by calling calloc with an appropriate size, which would be incredibly fast.
更多推荐
F#:为什么Array.createZero这么快?
发布评论