Skip to content

Instantly share code, notes, and snippets.

@cartermp
Created October 18, 2021 22:39
Show Gist options
  • Save cartermp/3179ab38d305cee9a517f4642b9964b7 to your computer and use it in GitHub Desktop.
Save cartermp/3179ab38d305cee9a517f4642b9964b7 to your computer and use it in GitHub Desktop.
// Learn more about F# at http://docs.microsoft.com/dotnet/fsharp
open BenchmarkDotNet.Attributes
open BenchmarkDotNet.Running
let MAGIC = 7
let simple n =
n &&& 0xFF
let optional n =
let i = n &&& 0xFF
if i = MAGIC then None else Some i
let voptional n =
let i = n &&& 0xFF
if i = MAGIC then ValueNone else ValueSome i
[<MemoryDiagnoser>]
type OptionBench() =
[<Benchmark(Baseline=true)>]
member _.Simple() =
let mutable sum = 0
for i in 0..1_000 do
let n = simple i
if n <> MAGIC then
sum <- sum + n
sum
[<Benchmark>]
member _.Optional() =
let mutable sum = 0
for i in 0..1_000 do
let n = optional i
match n with
| Some n ->
sum <- sum + n
| None -> ()
sum
[<Benchmark>]
member _.VOptional() =
let mutable sum = 0
for i in 0..1_000 do
let n = voptional i
match n with
| ValueSome n ->
sum <- sum + n
| ValueNone -> ()
sum
[<EntryPoint>]
let main argv =
BenchmarkRunner.Run<OptionBench>() |> ignore
0 // return an integer exit code
BenchmarkDotNet=v0.13.1, OS=Windows 10.0.19042.1288 (20H2/October2020Update)
AMD Ryzen 9 5900X, 1 CPU, 24 logical and 12 physical cores
.NET SDK=6.0.100-rc.2.21505.57
  [Host]     : .NET 6.0.0 (6.0.21.48005), X64 RyuJIT DEBUG
  DefaultJob : .NET 6.0.0 (6.0.21.48005), X64 RyuJIT

Method Mean Error StdDev Ratio RatioSD Gen 0 Allocated
Simple 232.3 ns 3.57 ns 3.16 ns 1.00 0.00 - -
Optional 2,284.6 ns 9.22 ns 8.17 ns 9.84 0.12 1.4267 23,928 B
VOptional 448.8 ns 4.88 ns 4.57 ns 1.93 0.03 - -
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment