I am working with a an array of 5 character strings. And joining the items into one large string. x
is the array and looks like this:
val x : System.String [] =
[|"W0SPFR"; "1BUDJY"; "1L1RJV"; "ITBPFA"; "QVUS7N"; "CJ6ZMQ"; "V3HUQ5";
"694L4U"; "8RYWPF"; "YGWS8U"; "3KEKA9"; "1C9L6Q"; "OXCGSF"; "GF0CUQ";
"YR41AF"; "4D4U0G"; "1U94T1"; "VUVJI0"; "CTYQL3"; "310XVU"; ...|]
My initial attempt was this:
let y = x |> Array.reduce (fun x y -> x+"-"+y)
Unfortunately this turned out to be slow, even for moderately sized arrays (10,000 elements). I'm looking to scale this up to millions.
Real: 00:00:00.483, CPU: 00:00:00.577, GC gen0: 167, gen1: 6, gen2: 5
My second attempt was better:
open System.Text
let buf = new System.Text.StringBuilder()
let z = x |> Array.fold (fun (buf:StringBuilder) x -> buf.Append(x+"-")) buf |> string
z.[0..(z |> Seq.length)-2] = y
Question1:
Is StringBuilder the fastest way to build this large string?
I'm also open to parallelizing it.
Question2:
Because I use fold in the second attempt, a -
is being joined to the last item, hence I'm getiing rid of it with z.[0..(z |> Seq.length)-2]
.
Is there a more elegant way?