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

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

我有这样的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这么快?

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

发布评论

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

>www.elefans.com

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