haskell / text

Haskell library for space- and time-efficient operations over Unicode text.

Home Page:http://hackage.haskell.org/package/text

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Optimize cons by checking if the existing array can be used

ezacharias opened this issue · comments

A possible optimization for cons is to check if the character at offset-1 in the array is the same as the one being consed, and if so, return a text using that array rather than creating a new array. Here is an implementation in the 2.0.1 version of the library.

myCons :: Char -> Text -> Text
myCons w t@(Text arr off len)
  | eqPrev = Text arr (off + d) (len - d)
  | otherwise = cons w t
  where eqPrev = off > 0 && c == w
        Iter c d = reverseIter t (-1)

I'm not sure if this optimization would occur enough to justify the test. Still, I hope you find it interesting if you haven't considered it already.

That's an interesting trick! It does seem too small in applicability to include in text. But it seems at least generalizable to append, and if there are enough tricks for reusing text values like that, they could make a nice little library. Thank you for bringing this up!

cc @haskell/text