继续我的 F# 性能测试。有关更多背景信息,请参见此处:
f# 结构构造函数中的 NativePtr.stackalloc
现在我已经在 F# 中使用了堆栈数组。但是,出于某种原因,等效的 C# 大约快了 50 倍。我在下面包含了 ILSpy 反编译版本,看起来只有 1 行是真正不同的(在 stackAlloc 中)。
这里发生了什么?未经检查的算术真的是造成这种巨大差异的原因吗?不知道我怎么能测试这个??
https://msdn.microsoft.com/en-us/library/a569z7k8.aspx
F# 代码
#nowarn "9"
open Microsoft.FSharp.NativeInterop
open System
open System.Diagnostics
open System.Runtime.CompilerServices
[<MethodImpl(MethodImplOptions.NoInlining)>]
let stackAlloc x =
let mutable ints:nativeptr<byte> = NativePtr.stackalloc x
()
[<EntryPoint>]
let main argv =
printfn "%A" argv
let size = 8192
let reps = 10000
stackAlloc size // JIT
let clock = Stopwatch()
clock.Start()
for i = 1 to reps do
stackAlloc …Run Code Online (Sandbox Code Playgroud) 我正在进行一些 F# 性能测试,并尝试在堆栈上而不是堆上创建一个数组(值与引用类型)。我正在使用 NativePtr.stackalloc 在堆栈上分配内存。在下面的第一个构造函数中出现错误。
type StackArray<'T when 'T : unmanaged> =
struct
val pointer: nativeptr<'T>
new(x) = { pointer = NativePtr.stackalloc x}
new(pointer) = { pointer = pointer}
end
// This give a System.TypeInitializationException with internal System.InvalidProgramException
let ints2 = new StackArray<int>(10)
// This works fine
let (pointer:nativeptr<int>) = NativePtr.stackalloc 10
let ints = new StackArray<int>(pointer)
Run Code Online (Sandbox Code Playgroud)
我可以简单地在函数中使用第二种方法,但是为什么我无法在构造函数内分配内存,这真的很困扰我。