Skip to content

Instantly share code, notes, and snippets.

@thomasjm
Last active October 30, 2023 05:34
Show Gist options
  • Save thomasjm/7c2bd4f25ba4a75e90b898a902725ead to your computer and use it in GitHub Desktop.
Save thomasjm/7c2bd4f25ba4a75e90b898a902725ead to your computer and use it in GitHub Desktop.
Benchmarking Text to Vector conversion in Haskell
{-# LANGUAGE BangPatterns #-}
module Main (main) where
import Control.Monad
import Data.Maybe
import Data.String.Interpolate
import Data.Text as T
import qualified Data.Vector.Unboxed as VU
import Weigh
testFunc :: Int -> Text -> Weigh ()
testFunc inputSize text = wgroup [i|#{inputSize} characters|] $ do
func' "VU.fromList" fromListMethod text
func' "VU.fromListN" fromListNMethod text
func' "generate" generateMethod text
func' "unfoldr" unfoldrMethod text
func' "unfoldrN" unfoldrNMethod text
func' "unfoldrExactN" unfoldrExactNMethod text
fromListMethod :: Text -> VU.Vector Char
fromListMethod = VU.fromList . T.unpack
fromListNMethod :: Text -> VU.Vector Char
fromListNMethod t = VU.fromListN (T.length t) (T.unpack t)
-- | This one has great allocation but it's O(n^2) time!
generateMethod :: Text -> VU.Vector Char
generateMethod t = VU.generate (T.length t) (T.index t)
unfoldrMethod :: Text -> VU.Vector Char
unfoldrMethod = VU.unfoldr T.uncons
unfoldrNMethod :: Text -> VU.Vector Char
unfoldrNMethod t = VU.unfoldrN (T.length t) T.uncons t
unfoldrExactNMethod :: Text -> VU.Vector Char
unfoldrExactNMethod t = VU.unfoldrExactN (T.length t) (fromJust . T.uncons) t
main :: IO ()
main = mainWith $
forM_ [10, 100, 1000, 10000, 100000] $ \n -> do
let !text = T.replicate n "0"
testFunc n text
Benchmark myers-diff-weigh-text-to-vector: RUNNING...
10 characters
Case Allocated GCs
VU.fromList 1,000 0
VU.fromListN 888 0
generate 104 0
unfoldr 304 0
unfoldrN 792 0
unfoldrExactN 792 0
100 characters
Case Allocated GCs
VU.fromList 8,424 0
VU.fromListN 7,728 0
generate 464 0
unfoldr 1,248 0
unfoldrN 7,632 0
unfoldrExactN 7,632 0
1000 characters
Case Allocated GCs
VU.fromList 80,440 0
VU.fromListN 76,128 0
generate 4,064 0
unfoldr 8,464 0
unfoldrN 76,032 0
unfoldrExactN 76,032 0
10000 characters
Case Allocated GCs
VU.fromList 851,384 0
VU.fromListN 760,128 0
generate 40,064 0
unfoldr 131,408 0
unfoldrN 760,032 0
unfoldrExactN 760,032 0
100000 characters
Case Allocated GCs
VU.fromList 8,248,936 1
VU.fromListN 7,600,128 1
generate 400,640 1
unfoldr 1,048,960 0
unfoldrN 7,600,032 1
unfoldrExactN 7,600,032 1
Benchmark myers-diff-weigh-text-to-vector: FINISH
Completed 2 action(s).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment