F#: Why is Array.createZero so fast? -
i have 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 , had these results:
0ms 200ms how array.zerocreate create array fast , it's guaranteed it's elements have default value? in other languages know there no such possibilities (as far know). in other languages know fast initialization of array elements not guaranteed have default value, because can initialized in memory garbage lies.
thanks!
so can go , source:
[<compiledname("zerocreate")>] allow zerocreate count = if count < 0 invalidarg "count" (sr.getstring(sr.inputmustbenonnegative)) microsoft.fsharp.primitives.basics.array.zerocreateunchecked count and
[<compiledname("create")>] allow create (count:int) (x:'t) = if count < 0 invalidarg "count" (sr.getstring(sr.inputmustbenonnegative)) allow array = (microsoft.fsharp.primitives.basics.array.zerocreateunchecked count : 't[]) = 0 operators.checked.(-) count 1 // utilize checked arithmetic here satisfy fxcop array.[i] <- x array so can see create more work - slower.
we can go deeper , find underlying function:
// input parameter should checked callers if necessary allow inline zerocreateunchecked (count:int) = (# "newarr !0" type ('t) count : 't array #) this executes cil newarr instruction.
this instruction quite conceiveably executed calling calloc appropriate size, incredibly fast.
arrays f# initialization array-initialization
No comments:
Post a Comment