Builders are used to efficiently construct sequences of bytes from
smaller parts.
Typically,
such a construction is part of the implementation of an encoding, i.e.,
a function for converting Haskell values to sequences of bytes.
Examples of encodings are the generation of the sequence of bytes
representing a HTML document to be sent in a HTTP response by a
web application or the serialization of a Haskell value using
a fixed binary format.
For an efficient implementation of an encoding,
it is important that (a) little time is spent on converting
the Haskell values to the resulting sequence of bytes and
(b) that the representation of the resulting sequence
is such that it can be consumed efficiently.
Builders support (a) by providing an O(1) concatentation operation
and efficient implementations of basic encodings for Chars, Ints,
and other standard Haskell values.
They support (b) by providing their result as a L.LazyByteString,
which is internally just a linked list of pointers to chunks
of consecutive raw memory.
L.LazyByteStrings can be efficiently consumed by functions that
write them to a file or send them over a network socket.
Note that each chunk boundary incurs expensive extra work (e.g., a system call)
that must be amortized over the work spent on consuming the chunk body.
Builders therefore take special care to ensure that the
average chunk size is large enough.
The precise meaning of large enough is application dependent.
The current implementation is tuned
for an average chunk size between 4kb and 32kb,
which should suit most applications.
As a simple example of an encoding implementation,
we show how to efficiently convert the following representation of mixed-data
tables to an UTF-8 encoded Comma-Separated-Values (CSV) table.
data Cell = StringC String
| IntC Int
deriving( Eq, Ord, Show )
type Row = [Cell]
type Table = [Row]
CSV is a character-based representation of tables. For maximal modularity,
we could first render Tables as Strings and then encode this String
using some Unicode character encoding. However, this sacrifices performance
due to the intermediate String representation being built and thrown away
right afterwards. We get rid of this intermediate String representation by
fixing the character encoding to UTF-8 and using Builders to convert
Tables directly to UTF-8 encoded CSV tables represented as
L.LazyByteStrings.
Note that the ASCII encoding is a subset of the UTF-8 encoding,
which is why we can use the optimized function intDec to
encode an Int as a decimal number with UTF-8 encoded digits.
Using intDec is more efficient than stringUtf8 . show,
as it avoids constructing an intermediate String.
Avoiding this intermediate data structure significantly improves
performance because encoding Cells is the core operation
for rendering CSV-tables.
See Data.ByteString.Builder.Prim for further
information on how to improve the performance of renderString.
We demonstrate our UTF-8 CSV encoding function on the following table.
We can clearly see that we are converting to a binary format. The 'λ'
and 'ö' characters, which have a Unicode codepoint above 127, are
expanded to their corresponding UTF-8 multi-byte representation.
import Criterion.Main -- add this import to the ones above
maxiTable :: Table
maxiTable = take 1000 $ cycle table
main :: IO ()
main = defaultMain
[ bench "encodeUtf8CSV maxiTable (original)" $
whnf (L.length . encodeUtf8CSV) maxiTable
]
On a Core2 Duo 2.20GHz on a 32-bit Linux,
the above code takes 1ms to generate the 22'500 bytes long L.LazyByteString.
Looking again at the definitions above,
we see that we took care to avoid intermediate data structures,
as otherwise we would sacrifice performance.
For example,
the following (arguably simpler) definition of renderRow is about 20% slower.
Similarly, using O(n) concatentations like ++ or the equivalent concat
operations on strict and L.LazyByteStrings should be avoided.
The following definition of renderString is also about 20% slower.
Apart from removing intermediate data-structures,
encodings can be optimized further by fine-tuning their execution
parameters using the functions in Data.ByteString.Builder.Extra and
their "inner loops" using the functions in
Data.ByteString.Builder.Prim.
IsListBuilderDefined in bytestring-0.12.2.0 · Data.ByteString.Builder.Internal
For long or infinite lists use fromList because it uses LazyByteString otherwise use fromListN which uses StrictByteString.
ShowBuilderDefined in bytestring-0.12.2.0 · Data.ByteString.Builder · orphan
IsStringBuilderDefined in bytestring-0.12.2.0 · Data.ByteString.Builder · orphan
SemigroupBuilderDefined in bytestring-0.12.2.0 · Data.ByteString.Builder.Internal
MonoidBuilderDefined in bytestring-0.12.2.0 · Data.ByteString.Builder.Internal
typeItemBuilder = Word8Defined in bytestring-0.12.2.0 · Data.ByteString.Builder.Internal
Executing Builders
3 declarations
Internally, Builders are buffer-filling functions. They are
executed by a driver that provides them with an actual buffer to
fill. Once called with a buffer, a Builder fills it and returns a
signal to the driver telling it that it is either done, has filled the
current buffer, or wants to directly insert a reference to a chunk of
memory. In the last two cases, the Builder also returns a
continuation Builder that the driver can call to fill the next
buffer. Here, we provide the two drivers that satisfy almost all use
cases. See Data.ByteString.Builder.Extra, for information
about fine-tuning them.
Execute a Builder and return the generated chunks as a LazyByteString.
The work is performed lazy, i.e., only when a chunk of the LazyByteString
is forced.
Output a Builder to a Handle.
The Builder is executed directly on the buffer of the Handle. If the
buffer is too small (or not present), then it is replaced with a large
enough buffer.
It is recommended that the Handle is set to binary and
System.IO.BlockBuffering mode. See System.IO.hSetBinaryMode and
System.IO.hSetBuffering.
This function is more efficient than hPut . toLazyByteString because in
many cases no buffer allocation has to be done. Moreover, the results of
several executions of short Builders are concatenated in the Handles
buffer, therefore avoiding unnecessary buffer flushes.
Create a Builder denoting the same sequence of bytes as a
StrictByteString.
The Builder inserts large StrictByteStrings directly, but copies small ones
to ensure that the generated chunks are large on average.
Create a Builder denoting the same sequence of bytes as a lazy
LazyByteString.
The Builder inserts large chunks of the LazyByteString directly,
but copies small ones to ensure that the generated chunks are large on
average.
The ASCII encoding is a 7-bit encoding. The Char7 encoding implemented here
works by truncating the Unicode codepoint to 7-bits, prefixing it
with a leading 0, and encoding the resulting 8-bits as a single byte.
For the codepoints 0-127 this corresponds the ASCII encoding.
The ISO/IEC 8859-1 encoding is an 8-bit encoding often known as Latin-1.
The Char8 encoding implemented here works by truncating the Unicode codepoint
to 8-bits and encoding them as a single byte. For the codepoints 0-255 this corresponds
to the ISO/IEC 8859-1 encoding.
The UTF-8 encoding can encode all Unicode codepoints. We recommend
using it always for encoding Chars and Strings unless an application
really requires another encoding.