on master help sign in
Use roundUpToPower2 in snoc
commit37d3c17e05ce80d9c11ea6039eebb6642776ead8 authorHarendra Kumar <harendra@composewell.com> dateSun 9 Jan 2022, 22:22 (5 years ago) parentca8bfc5
1 file changed+19−6
src/Streamly/Internal/Data/Array/Foreign/Mut/Type.hs+19−6
src/Streamly/Internal/Data/Array/Foreign/Mut/Type.hs+19−6
@@ -720,6 +720,7 @@ blockSize = 4 * 1024
720720largeObjectThreshold :: Int
721721largeObjectThreshold = (blockSize * 8) `div` 10
722722
723+-- XXX Should be done only when we are using the GHC allocator.
723724-- | Round up an array larger than 'largeObjectThreshold' to use the whole
724725-- block.
725726{-# INLINE roundUpLargeArray #-}
@@ -732,16 +733,23 @@ roundUpLargeArray size =
732733 ((size + blockSize - 1) .&. negate blockSize)
733734 else size
734735
736+{-# INLINE isPower2 #-}
737+isPower2 :: Int -> Bool
738+isPower2 n = n .&. (n - 1) == 0
739+
740+{-# INLINE roundUpToPower2 #-}
735741roundUpToPower2 :: Int -> Int
736−roundUpToPower2 x =
742+roundUpToPower2 n =
737743#if WORD_SIZE_IN_BITS == 64
738744 1 + z6
739745#else
740746 1 + z5
741747#endif
748+
742749 where
743− z = x - 1
744− z1 = z .|. z `shiftR` 1
750+
751+ z0 = n - 1
752+ z1 = z0 .|. z0 `shiftR` 1
745753 z2 = z1 .|. z1 `shiftR` 2
746754 z3 = z2 .|. z2 `shiftR` 4
747755 z4 = z3 .|. z3 `shiftR` 8
@@ -1007,8 +1015,6 @@ snocWith allocSize arr x = liftIO $ do
10071015snocLinear :: forall m a. (MonadIO m, Storable a) => Array a -> a -> m (Array a)
10081016snocLinear = snocWith (+ allocBytesToBytes (undefined :: a) arrayChunkBytes)
10091017
1010−-- XXX round it to next power of 2.
1011−--
10121018-- | The array is mutated to append an additional element to it. If there is no
10131019-- reserved space available in the array then it is reallocated to double the
10141020-- original size.
@@ -1025,7 +1031,14 @@ snocLinear = snocWith (+ allocBytesToBytes (undefined :: a) arrayChunkBytes)
10251031-- /Pre-release/
10261032{-# INLINE snoc #-}
10271033snoc :: forall m a. (MonadIO m, Storable a) => Array a -> a -> m (Array a)
1028−snoc = snocWith (* 2)
1034+snoc = snocWith f
1035+
1036+ where
1037+
1038+ f oldSize =
1039+ if isPower2 oldSize
1040+ then oldSize * 2
1041+ else roundUpToPower2 oldSize * 2
10291042
10301043-------------------------------------------------------------------------------
10311044-- Random reads