F #: Why is Array.createZero so fast?

I have this 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 got the following results:

0ms
200ms

How Array.zeroCreateto create an array so fast and it ensures that all its elements have a default value? In other languages, I know that there are no such possibilities (as far as I know). In other languages, I only know about quick array initialization, elements that do not have a guaranteed default value, because they can be initialized in the memory where some kind of garbage is.

Thank!

+3
source share
1 answer

So we can just take a look at 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

, Create - .

:

// The input parameter should be checked by callers if necessary
let inline zeroCreateUnchecked (count:int) =
    (# "newarr !0" type ('T) count : 'T array #)

CIL newarr.

, -, calloc , .

+6

All Articles