F#: Why is Array.createZero so fast?

前端 未结 1 1994
长发绾君心
长发绾君心 2020-12-21 09:08

I have this code:

let timer = new System.Diagnostics.Stopwatch()
timer.Start()
Array.zeroCreate 100000000

timer.Stop()
printfn \"%ims\" timer.Ela         


        
相关标签:
1条回答
  • 2020-12-21 09:59

    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
    

    and

        [<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 #)
    

    this basically just executes the CIL newarr instruction.

    This instruction could quite conceiveably be executed by calling calloc with an appropriate size, which would be incredibly fast.

    0 讨论(0)
提交回复
热议问题