F#:为什么 Array.createZero 这么快?

编程入门 行业动态 更新时间:2024-10-26 07:31:27
本文介绍了F#:为什么 Array.createZero 这么快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有这个代码:

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 这么快?

本文发布于:2023-10-15 12:04:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1494287.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Array   createZero

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!