[Haskell-cafe] ByteString and ByteString.Builder questions

Viktor Dukhovni ietf-dane at dukhovni.org
Wed Nov 29 23:27:18 UTC 2023


On Wed, Nov 29, 2023 at 12:24:17PM -0500, Viktor Dukhovni wrote:

> 
> > if I understand correctly, the ByteString.Builder is used to
> > efficiently construct sequence of bytes from smaller parts.
> 
> Best used in continuation-passing-style (right-associatively), where all
> the subsequent builders are lazily added as part of constructing the
> "head" builder. 
> 
>     builder = chunk1 <> (chunk2 <> (chunk3 <> (... <> chunkN)...))
> 
> Repeatedly appending tail chunks (effectively left-associate) is
> noticeably less efficient (similar to lists).  A work-around is to
> instead append (Builder->Builder) endomorphisms.
> 
>     b1 = Endo (mappend chunk1)
>     b2 = b1 <> Endo (mappend chunk2)
>     b3 = b2 <> Endo (mappend chunk3)
>     ...
>     bN = ...

Actually, this part is was a myth I failed to check, looking at the
`Builder` code, I see that builder `mappend` is already endomorphism
composition, so the extra wrapping is redundant.

So use builders for output, and don't attempt to model some hybrid of
builders and bytestrings.  It is rather unclear what problem that is
actually intended to solve.

-- 
    Viktor.


More information about the Haskell-Cafe mailing list