gpt4 book ai didi

performance - 几乎相同的方法之间的出色性能差异

转载 作者:行者123 更新时间:2023-12-03 17:03:27 25 4
gpt4 key购买 nike

在处理一个项目时,我无意中注意到,在启用优化的情况下,仅使用一个额外(未使用)参数的相同方法的运行速度甚至比另一个方法快十倍。

type Stream () =
static member private write (x, o, a : byte[]) = (for i = 0 to 3 do a.[o + i] <- byte((x >>> 24 - i * 8) % 256)); 4
static member private format f x l = Array.zeroCreate l |> fun a -> (f(x, 0, a) |> ignore; a)
static member private format1 f x l o = Array.zeroCreate l |> fun a -> (f(x, 0, a) |> ignore; a)
static member Format (value : int) = Stream.format (fun (x: int, i, a) -> Stream.write(x, i, a)) value 4
static member Format1 (value : int) = Stream.format1 (fun (x: int, i, a) -> Stream.write(x, i, a)) value 4

经过测试,Stream.Format1 运行速度比 Stream.Format 快得多,尽管私有(private)成员 Stream.formatStream.format1 只是 o 参数,而且方法本身未使用它。

编译器如何以如此不同的方式处理两个几乎相同的方法?

编辑:感谢您的解释,对我的无知深表歉意。

最佳答案

问题在于,当您仅使用一个参数调用 Format1 时,它只会返回一个函数。它还没有进行实际的格式化。这意味着如果您比较以下各项的性能:

Stream.Format 42
Stream.Format1 42

...那么您实际上是在比较第一种情况下实际格式化(创建数组并在其中写入内容)的性能以及不执行任何操作而仅返回函数值的代码的性能。

如果你没有使用 format1o 参数,那么你可以只传入一些虚拟值,以实际评估函数并获得结果.然后你应该得到类似的性能:

Stream.Format 42
Stream.Format1 42 ()

关于performance - 几乎相同的方法之间的出色性能差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8838083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com