F#,sprintf的性能%A「;论受歧视的工会
DU有许多非常有用的方面,包括内置的漂亮印刷。然而,令我惊讶的是,我简单的ToString函数使格式化DU的速度提高了1000倍以上。我错过什么了吗?F#,sprintf的性能%A「;论受歧视的工会,f#,F#,DU有许多非常有用的方面,包括内置的漂亮印刷。然而,令我惊讶的是,我简单的ToString函数使格式化DU的速度提高了1000倍以上。我错过什么了吗?sprintf“%A”比我的ToString函数做的更多是什么 type XYZ = |X of float |Y of float*float |Z let ar = // some test Array [| for i in 1..3000 do for a in [ X(1.) ; Y(2.,3.)
sprintf“%A”
比我的ToString函数做的更多是什么
type XYZ =
|X of float
|Y of float*float
|Z
let ar = // some test Array
[| for i in 1..3000 do for a in [ X(1.) ; Y(2.,3.) ; Z ] do yield a |]
let xyzToString (x:XYZ) =
match x with
|X (a) -> sprintf "X %.1f" a
|Y (a,b)-> sprintf "Y (%.1f,%.1f)" a b
|Z -> "Z"
#time
ar|> Array.map (fun x -> sprintf "%s" (xyzToString x) ) // about 15 ms
ar|> Array.map (fun x -> sprintf "%A" x ) // about 4000 ms
sprintf“%A”
正在运行时执行一些操作,以确定正在打印的对象的类型和结构,这非常耗时
您的版本在编译时绑定到一个特定类型(
XYZ
),这使得它更加高效。正如@Mau所指出的,您的比较不是一成不变的printf
接受任何类型的参数。您的函数接受一个已知类型
如果这对您来说是一个真正的问题,并且您对更干净地封装解决方案感兴趣,您可以这样做:
type XYZ =
|X of float
|Y of float*float
|Z
override this.ToString() =
match this with
|X (a) -> sprintf "X %.1f" a
|Y (a,b)-> sprintf "Y (%.1f,%.1f)" a b
|Z -> "Z"
...
ar|> Array.map (fun x -> sprintf "%O" x )
相关:大量的解析。。。它与DU无关,而是与
sprintf
的工作方式有关