【发布时间】:2012-01-12 15:58:22
【问题描述】:
在处理一个项目时,我无意中注意到,在启用优化的情况下,只有一个额外(未使用)参数的相同方法的运行速度甚至比另一个快十倍。
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 快得多,尽管私有成员 Stream.format 和 Stream.format1 之间的唯一区别只是 o 参数,而且该方法本身并未使用该参数。
编译器如何以如此不同的方式处理两个几乎相同的方法?
编辑:感谢您的解释,并为无知感到抱歉。
【问题讨论】:
-
您运行了多少次迭代来获得时间?一?一百万?您需要使您的示例足够广泛,以消除缓存效果、内核调度等。
标签: performance optimization compiler-construction f#