Skip to content

Instantly share code, notes, and snippets.

@En3Tho
Created November 16, 2020 10:54
Show Gist options
  • Save En3Tho/a35c9e318e0e8f09ed9231212a225f0f to your computer and use it in GitHub Desktop.
Save En3Tho/a35c9e318e0e8f09ed9231212a225f0f to your computer and use it in GitHub Desktop.
module Benchmarks.FSharp.FormatBenchmark
open System
open System.Text
open BenchmarkDotNet.Attributes
open BenchmarkDotNet.Jobs
let ignoreFormatting = String.Equals("abc", "ABC", StringComparison.OrdinalIgnoreCase)
let inline ignoreAndReturnDefault _ = Unchecked.defaultof<'b>
type T = T with
static member inline ($) (T, arg: unit) = ()
static member inline ($) (T, arg: int) = 0 // mandatory second terminal case; is unused in runtime but is required for the code to compile
static member inline ($) (T, func: ^a -> ^b) : ^a -> ^b = fun (_ : 'a) -> T $ Unchecked.defaultof<'b>
let inline negate() : 'a = T $ Unchecked.defaultof<'a>
let inline debugLog format : 'a =
if ignoreFormatting then
T $ Unchecked.defaultof<'a>
else
Printf.kprintf (printfn "%A: %s" DateTime.Now) format
[<MemoryDiagnoser>]
[<SimpleJob(RuntimeMoniker.NetCoreApp31)>]
[<SimpleJob(RuntimeMoniker.NetCoreApp50)>]
type Formatter() =
let someNum = DateTime.Now.Millisecond;
let someString = DateTime.Now.ToString()
let someDate = DateTime.Now
let sb = StringBuilder(128)
[<Benchmark>]
member _.FormatSprintf() = sprintf "%i %s %O" someNum someString someDate
[<Benchmark>]
member _.FormatStringFormat() = String.Format("{0} {1} {2}", someNum, someString, someDate)
[<Benchmark>]
member _.FormatSB() = Printf.bprintf sb "%i %s %O" someNum someString someDate
let result = sb.ToString()
sb.Clear() |> ignore
result
[<Benchmark>]
member _.FormatInterpolation() = $"{someNum} {someString} {someDate}"
[<Benchmark>]
member _.DebugLogCustomFormat() = debugLog "%i %s %O %A" someNum someString someDate (Exception "")
[<Benchmark>]
member _.DebugLogStringFormat() = debugLog "sdassda"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment