Skip to content

Commit

Permalink
Hand SAT optimization for Data.ByteString.unfoldrN (haskell#356)
Browse files Browse the repository at this point in the history
* appropriate unfoldrN benchmark

* Hand SAT optimization for Data.ByteString.unfoldrN

* inline createAndTrim'
  • Loading branch information
SkamDart authored and Bodigrim committed Jun 10, 2021
1 parent 4f6d727 commit 9df04a4
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 6 deletions.
14 changes: 8 additions & 6 deletions Data/ByteString.hs
Original file line number Diff line number Diff line change
Expand Up @@ -854,12 +854,14 @@ unfoldrN i f x0
| i < 0 = (empty, Just x0)
| otherwise = unsafePerformIO $ createAndTrim' i $ \p -> go p x0 0
where
go !p !x !n
| n == i = return (0, n, Just x)
| otherwise = case f x of
Nothing -> return (0, n, Nothing)
Just (w,x') -> do poke p w
go (p `plusPtr` 1) x' (n+1)
go !p !x !n = go' x n
where
go' !x' !n'
| n' == i = return (0, n', Just x')
| otherwise = case f x' of
Nothing -> return (0, n', Nothing)
Just (w,x'') -> do pokeByteOff p n' w
go' x'' (n'+1)
{-# INLINE unfoldrN #-}

-- ---------------------------------------------------------------------
Expand Down
1 change: 1 addition & 0 deletions Data/ByteString/Internal.hs
Original file line number Diff line number Diff line change
Expand Up @@ -564,6 +564,7 @@ createAndTrim' l f = do
else do ps <- create l' $ \p' ->
memcpy p' (p `plusPtr` off) l'
return (ps, res)
{-# INLINE createAndTrim' #-}

-- | Wrapper of 'Foreign.ForeignPtr.mallocForeignPtrBytes' with faster implementation for GHC
--
Expand Down
2 changes: 2 additions & 0 deletions bench/BenchAll.hs
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,8 @@ main = do
nf (S.foldl' (\acc x -> acc + fromIntegral x) (0 :: Int)) s) foldInputs
, bgroup "foldr'" $ map (\s -> bench (show $ S.length s) $
nf (S.foldr' (\x acc -> fromIntegral x + acc) (0 :: Int)) s) foldInputs
, bgroup "unfoldrN" $ map (\s -> bench (show $ S.length s) $
nf (S.unfoldrN (S.length s) (\a -> Just (a, a + 1))) 0) foldInputs
, bgroup "mapAccumL" $ map (\s -> bench (show $ S.length s) $
nf (S.mapAccumL (\acc x -> (acc + fromIntegral x, succ x)) (0 :: Int)) s) foldInputs
, bgroup "mapAccumR" $ map (\s -> bench (show $ S.length s) $
Expand Down

0 comments on commit 9df04a4

Please sign in to comment.