-- | Read a file line-by-line using handles, and perform a fold over the lines.-- The fold is used here to calculate the number of lines in the file.---- Tested in this benchmark:---- * Buffered, line-based IO--
{-# LANGUAGE BangPatterns #-}
module Benchmarks.FoldLines
( benchmark
) where
import Criterion (Benchmark, bgroup, bench)
import System.IO
import qualified Data.ByteString as B
import qualified Data.Text as T
import qualified Data.Text.IO as T
benchmark :: FilePath -> IOBenchmarkbenchmarkfp = return$bgroup"ReadLines"
[ bench"Text"$withHandle$foldLinesT (\n _ -> n+1) (0 :: Int)
, bench"ByteString"$withHandle$foldLinesB (\n _ -> n+1) (0 :: Int)
]
where
withHandlef = do
h <- openFilefpReadModehSetBufferingh (BlockBuffering (Just16384))
x <- fhhClosehreturnx-- | Text line fold--foldLinesT :: (a -> T.Text -> a) -> a -> Handle -> IOafoldLinesTfz0h = goz0
where
go !z = do
eof <- hIsEOFh
if eof
then returnz
else do
l <- T.hGetLineh
let z' = fzl in goz'{-# INLINE foldLinesT #-}-- | ByteString line fold--foldLinesB :: (a -> B.ByteString -> a) -> a -> Handle -> IOafoldLinesBfz0h = goz0
where
go !z = do
eof <- hIsEOFh
if eof
then returnz
else do
l <- B.hGetLineh
let z' = fzl in goz'{-# INLINE foldLinesB #-}