I'm writing some code that is rendering an HTML page (via servant, if that's relevant), and for various complicated reasons, I have to construct the HTML by "combining" two segments.
- One segment is fetched from an internal HTTP API which returns a
Data.ByteString.Lazy - The other segment is rendered using the
edelibrary, which generates aData.Text.Lazy
What options do I have if I have to combine these two segments efficiently? The two segments can be reasonably large (few 100 kbs each). This servant server is going to see quite some traffic, so any inefficiency (like copying 100s of kbs of memory for every req/res, will quickly add up).
Assuming your endpoint returns a lazy
ByteString, use the functionencodeUtf8fromData.Text.Lazy.Encodingto convert your lazyTextinto a lazyByteString, and then return theappendof the two lazyByteStrings.Internally, lazy
ByteStrings are basically lists of strictByteStringchunks. Concatenating them is list concatenation, and doesn't incur in new allocations for the bytes themselves.If you had a large number of lazy
ByteStrings instead of two, you should take the extra step of usinglazyByteStringto convert them toBuilders, concatenate theBuilders, and then get the result lazyByteStringusingtoLazyByteString. This will avoid the inefficiency of left-associated list concatenation.