From dca4e0b636f7001f17a8d270fca7725de6bb6c2a Mon Sep 17 00:00:00 2001 From: Mitchell Rosen Date: Wed, 24 May 2023 09:27:25 -0400 Subject: [PATCH] add Proem.Text.fromInt --- .gitignore | 1 + bench/Main.hs | 16 ++++++++++++++++ proem.cabal | 15 +++++++++++++++ src/Proem/Text.hs | 27 +++++++++++++++++++++++++++ 4 files changed, 59 insertions(+) create mode 100644 bench/Main.hs create mode 100644 src/Proem/Text.hs diff --git a/.gitignore b/.gitignore index c33954f..d9abb95 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ dist-newstyle/ +Session.vim diff --git a/bench/Main.hs b/bench/Main.hs new file mode 100644 index 0000000..010df99 --- /dev/null +++ b/bench/Main.hs @@ -0,0 +1,16 @@ +module Main where + +import Data.Text qualified as Text +import Data.Text.Lazy qualified as Text.Lazy +import Data.Text.Lazy.Builder qualified as Text.Lazy.Builder +import Data.Text.Lazy.Builder.Int qualified as Text.Lazy.Builder +import ParkBench +import Proem.Text qualified + +main :: IO () +main = do + benchmark + [ function "pack . show" (Text.pack . show) (-1000), + function "toStrict . toLazyText . decimal" (Text.Lazy.toStrict . Text.Lazy.Builder.toLazyText . Text.Lazy.Builder.decimal) (-1000), + function "Proem.Text.fromInt" Proem.Text.fromInt (-1000) + ] diff --git a/proem.cabal b/proem.cabal index 83d3731..4b12652 100644 --- a/proem.cabal +++ b/proem.cabal @@ -46,6 +46,7 @@ library Proem.File Proem.List Proem.Seq + Proem.Text hs-source-dirs: src default-language: Haskell2010 ghc-options: @@ -63,3 +64,17 @@ library if impl(ghc >= 9.2) ghc-options: -Wno-missing-kind-signatures + +benchmark bench + build-depends: + base, + park-bench ^>= 0.1.0, + proem, + text, + default-extensions: + ImportQualifiedPost + hs-source-dirs: bench + default-language: Haskell2010 + ghc-options: -O -rtsopts -with-rtsopts=-T + main-is: Main.hs + type: exitcode-stdio-1.0 diff --git a/src/Proem/Text.hs b/src/Proem/Text.hs new file mode 100644 index 0000000..6e78bd1 --- /dev/null +++ b/src/Proem/Text.hs @@ -0,0 +1,27 @@ +module Proem.Text + ( fromInt, + ) +where + +import Data.Text (Text) +import qualified Data.Text as Text +import qualified Data.Text.Lazy as Text.Lazy +import qualified Data.Text.Lazy.Builder as Text.Lazy.Builder +import qualified Data.Text.Lazy.Builder.Int as Text.Lazy.Builder +import Prelude + +-- | Construct a text from an int. +fromInt :: Int -> Text +fromInt n = + -- Benchmarking seems to indicate going through a proper builder becomes faster at 5 characters + if n >= 0 + then if n < 9999 then stringy n else buildery n + else if n >= -999 then stringy n else buildery n + where + stringy :: Int -> Text + stringy = + Text.pack . show + + buildery :: Int -> Text + buildery = + Text.Lazy.toStrict . Text.Lazy.Builder.toLazyText . Text.Lazy.Builder.decimal