immutability - Is using a StringBuilder a right thing to do in F#? -
stringbuiler mutable object, f# encourages employing immutability as possible. 1 should use transformation rather mutation. apply stringbuilder when comes building string in f#? there f# immutable alternative it? if so, alternative efficient?
i think using stringbuilder
in f# fine - fact sb.append
returns current instance of stringbuilder
means can used fold
function. though still imperative (the object mutated), fits reasonably functional style when not expose references stringbuilder
.
but equally, can construct list of strings , concatenate them using string.concat
- efficient using stringbuilder
(it slower, not - , faster concatenating strings using +
)
so, lists give similar performance, immutable (and work concurrency etc.) - fit if building string algorithmically, because can append strings front of list - efficient operation on lists (and reverse string). also, using list expressions gives convenient syntax:
// concatenating strings using + (2.3 seconds) let s1 = [ in 0 .. 25000 -> "hello " ] |> seq.reduce (+) s1.length // creating immutable list , using string.concat (5 ms) let s2 = [ in 0 .. 25000 -> "hello " ] |> string.concat "" s2.length // creating lazy sequence , concatenating using stringbuilder & fold (5 ms) let s3 = seq { in 0 .. 25000 -> "hello " } |> seq.fold(fun (sb:system.text.stringbuilder) s -> sb.append(s)) (new system.text.stringbuilder()) |> fun x -> x.tostring() s3.length // imperative solution using stringbuilder , loop (1 ms) let s4 = ( let sb = new system.text.stringbuilder() in 0 .. 25000 sb.append("hello ") |> ignore sb.tostring() ) s4.length
the times measured on my, fast, work machine using #time
in f# interactive - quite faster in release build, think representative.
Comments
Post a Comment