Skip to content

Instantly share code, notes, and snippets.

@latkin latkin/code.fsx
Last active Aug 29, 2015

Embed
What would you like to do?
Benchmark of groupBy perf
open System.Collections.Generic
open System.Diagnostics
let groupBy keyMaker elements =
elements |> Seq.groupBy keyMaker |> Seq.length
let loopGroup keyMaker elements =
let d = Dictionary<string, seq<'a>>()
for p in elements do
let key = keyMaker p
if d.ContainsKey(key) then d.[key] <- (Seq.append d.[key] [|p|])
else d.Add(key, [|p|])
d |> Seq.cast<KeyValuePair<_,_>> |> Seq.length
let timeit f = Stopwatch.StartNew() |> (fun sw -> (f (), sw.Elapsed.TotalSeconds))
let rnd = System.Random()
let data = Array.init 1000000 (fun _ -> rnd.Next(1000))
[1..5] |> List.iter (fun _ -> timeit (fun _ -> groupBy (fun n -> n.ToString()) data) |> printfn "groupBy %A" )
[1..5] |> List.iter (fun _ -> timeit (fun _ -> loopGroup (fun n -> n.ToString()) data) |> printfn "loopGroup %A" )
// F# 3.1 results
// groupBy (1000, 0.3984047)
// groupBy (1000, 0.346236)
// groupBy (1000, 0.3270108)
// groupBy (1000, 0.3249828)
// groupBy (1000, 0.3991331)
// loopGroup (1000, 0.8852538)
// loopGroup (1000, 0.8283647)
// loopGroup (1000, 0.9569686)
// loopGroup (1000, 0.8888318)
// loopGroup (1000, 0.9748136)
// F# 4.0 results
// groupBy (1000, 0.1995975)
// groupBy (1000, 0.1632741)
// groupBy (1000, 0.1873295)
// groupBy (1000, 0.1631585)
// groupBy (1000, 0.1628704)
// loopGroup (1000, 0.8894845)
// loopGroup (1000, 0.9352174)
// loopGroup (1000, 0.9339083)
// loopGroup (1000, 0.8045598)
// loopGroup (1000, 1.0230667)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.