Skip to content

Commit 888b977

Browse files
kuk0hvr
authored andcommitted
faster replicate
instead of using memcpy to copy the text n times, we double the copied text every iteration, thus calling the super-fast memcpy only ~log n times (with larger and larger chunks to copy)
1 parent e297190 commit 888b977

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

Data/Text.hs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,7 @@ import Data.Text.Internal.Unsafe.Char (unsafeChr)
243243
import qualified Data.Text.Internal.Functions as F
244244
import qualified Data.Text.Internal.Encoding.Utf16 as U16
245245
import Data.Text.Internal.Search (indices)
246+
import Data.Text.Internal.Unsafe.Shift (UnsafeShift(..))
246247
#if defined(__HADDOCK__)
247248
import Data.ByteString (ByteString)
248249
import qualified Data.Text.Lazy as L
@@ -1110,12 +1111,15 @@ replicate n t@(Text a o l)
11101111
x :: ST s (A.MArray s)
11111112
x = do
11121113
arr <- A.new len
1113-
let loop !d !i | i >= n = return arr
1114-
| otherwise = let m = d + l
1115-
in A.copyI arr d a o m >> loop m (i+1)
1116-
loop 0 0
1114+
A.copyI arr 0 a o l
1115+
let loop !l =
1116+
let l2 = l `shiftL` 1 in
1117+
if l2 > len then A.copyM arr l arr 0 (len - l) >> return arr
1118+
else A.copyM arr l arr 0 l >> loop l2
1119+
loop l
11171120
{-# INLINE [1] replicate #-}
11181121

1122+
11191123
{-# RULES
11201124
"TEXT replicate/singleton -> replicateChar" [~1] forall n c.
11211125
replicate n (singleton c) = replicateChar n c

0 commit comments

Comments
 (0)