Skip to content

Instantly share code, notes, and snippets.

@mausch
Created September 6, 2013 04:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mausch/6459715 to your computer and use it in GitHub Desktop.
Save mausch/6459715 to your computer and use it in GitHub Desktop.
let n = 25000
// Concatenating strings using + (2.3 seconds)
let s1 = [ for i in 0 .. n -> "Hello " ] |> Seq.reduce (+)
s1.Length
// Creating immutable list and using String.concat (5 ms)
let s2 = [ for i in 0 .. n -> "Hello " ] |> String.concat ""
s2.Length
// Creating a lazy sequence and concatenating using StringBuilder & fold (5 ms)
let s3 =
seq { for i in 0 .. n -> "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 and for loop (1 ms)
let s4 =
let sb = new System.Text.StringBuilder()
for i in 0 .. n do sb.Append("Hello ") |> ignore
sb.ToString()
s4.Length
// List rev (5 ms)
let s5 =
seq { for i in 0 .. n -> "Hello " }
|> Seq.fold (fun xs x -> x::xs) []
|> Seq.toList
|> List.rev
|> String.concat ""
s5.Length
// FSharpx DList (35 ms)
#r @"g:\prg\FSharpx\build\Debug\FSharpx.Core.dll"
open FSharpx
open FSharpx.Collections
let s6 =
seq { for i in 0 .. n -> "Hello " }
|> Seq.fold (flip DList.conj) DList.empty
|> String.concat ""
s6.Length
// A simple function-based DList (5 ms)
type 'a DList1 = 'a list -> 'a list
module DList1 =
let empty : 'a DList1 = id
let inline snoc (l: _ DList1) x : _ DList1 = (fun xs -> x::xs) << l
let toList (l: _ DList1) = l []
let s7 =
seq { for i in 0 .. n -> "Hello " }
|> Seq.fold DList1.snoc DList1.empty
|> DList1.toList
|> String.concat ""
s7.Length
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment