F#,sprintf"%A"在被歧视的联盟中的表现

Gos*_*win 2 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.) ; 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
Run Code Online (Sandbox Code Playgroud)

Mau*_*Mau 5

sprintf "%A"在运行时进行一些反射以确定正在打印的对象的类型和结构,这非常耗时.

您的版本XYZ在编译时绑定到特定类型(),使其更有效.