作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
引用此代码:F# Static Member Type Constraints
为什么是,例如,
let gL = G_of 1L
[1L..100000L] |> List.map (fun n -> factorize gL n)
[1L..100000L] |> List.map (fun n -> factorize (G_of 1L) n)
最佳答案
反射器显示 test2() 变成了 4 个类,而 test1() 变成了两个类。这仅在 Debug模式下发生。 Reflector 在 Release模式下显示相同的代码(每个类一个)。不幸的是,当我尝试在 C# 中查看源代码时,Reflector 崩溃了,并且 IL 非常长。
let test1() =
let gL = G_of 1L
[1L..1000000L] |> List.map (fun n -> factorize gL n)
let test2() =
[1L..1000000L] |> List.map (fun n -> factorize (G_of 1L) n)
let sw = Stopwatch.StartNew()
test1() |> ignore
sw.Stop()
Console.WriteLine("test1 {0}ms", sw.ElapsedMilliseconds)
let sw2 = Stopwatch.StartNew()
test2() |> ignore
sw2.Stop()
Console.WriteLine("test2 {0}ms", sw2.ElapsedMilliseconds)
test1 8216ms
test2 8237ms
test1 6654ms
test2 6680ms
test1 10304ms
test2 10348ms
test1 8858ms
test2 8977ms
open System
open System.Diagnostics
let inline zero_of (target:'a) : 'a = LanguagePrimitives.GenericZero<'a>
let inline one_of (target:'a) : 'a = LanguagePrimitives.GenericOne<'a>
let inline two_of (target:'a) : 'a = one_of(target) + one_of(target)
let inline three_of (target:'a) : 'a = two_of(target) + one_of(target)
let inline negone_of (target:'a) : 'a = zero_of(target) - one_of(target)
let inline any_of (target:'a) (x:int) : 'a =
let one:'a = one_of target
let zero:'a = zero_of target
let xu = if x > 0 then 1 else -1
let gu:'a = if x > 0 then one else zero-one
let rec get i g =
if i = x then g
else get (i+xu) (g+gu)
get 0 zero
type G<'a> = {
negone:'a
zero:'a
one:'a
two:'a
three:'a
any: int -> 'a
}
let inline G_of (target:'a) : (G<'a>) = {
zero = zero_of target
one = one_of target
two = two_of target
three = three_of target
negone = negone_of target
any = any_of target
}
let inline factorizeG n =
let g = G_of n
let rec factorize n j flist =
if n = g.one then flist
elif n % j = g.zero then factorize (n/j) j (j::flist)
else factorize n (j + g.one) (flist)
factorize n g.two []
let inline factorize (g:G<'a>) n = //'
let rec factorize n j flist =
if n = g.one then flist
elif n % j = g.zero then factorize (n/j) j (j::flist)
else factorize n (j + g.one) (flist)
factorize n g.two []
let test1() =
let gL = G_of 1L
[1L..100000L] |> List.map (fun n -> factorize gL n)
let test2() =
[1L..100000L] |> List.map (fun n -> factorize (G_of 1L) n)
let sw2 = Stopwatch.StartNew()
test1() |> ignore
sw2.Stop()
Console.WriteLine("test1 {0}ms", sw2.ElapsedMilliseconds)
let sw = Stopwatch.StartNew()
test2() |> ignore
sw.Stop()
Console.WriteLine("test2 {0}ms", sw.ElapsedMilliseconds)
Console.ReadLine() |> ignore
关于F# 性能问题 : what is the compiler doing?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2945880/
我是一名优秀的程序员,十分优秀!