Skip to content

Commit

Permalink
add Proem.Text.fromInt
Browse files Browse the repository at this point in the history
  • Loading branch information
mitchellwrosen committed May 24, 2023
1 parent 74eb50c commit dca4e0b
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
dist-newstyle/
Session.vim
16 changes: 16 additions & 0 deletions bench/Main.hs
Original file line number Diff line number Diff line change
@@ -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)
]
15 changes: 15 additions & 0 deletions proem.cabal
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ library
Proem.File
Proem.List
Proem.Seq
Proem.Text
hs-source-dirs: src
default-language: Haskell2010
ghc-options:
Expand All @@ -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
27 changes: 27 additions & 0 deletions src/Proem/Text.hs
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit dca4e0b

Please sign in to comment.