http-simple setRequestBodyLBS 背后的哲学

philosophy behind http-simple setRequestBodyLBS

我正在尝试使用 http-simple 库开发一个 http 客户端。该库的一些实现似乎让我感到困惑。

这个库大量使用了 Conduit;然而,还有这个 'setRequestBodyLBS' 函数,有趣的是,这里缺少函数 'setRequestBodyBS' 。据记载,Conduit 和 lazy IO 不能很好地协同工作。所以我的问题是,为什么不反过来呢?即,实现函数的 BS 版本而不是 LBS 版本?这里做出的选择背后的想法是什么?

在内部,惰性字节串就像严格字节串的链表。移动 from a strict bytestring to a lazy one is cheap (you build a linked list of one element) but going in the reverse direction 成本更高(您需要为合并的字节分配一个连续的内存块,然后从列表中复制每个块)。

Lazy IO 使用惰性字节串,但它们在其他情况下也很有用,例如当您有来自外部源的严格块并且您想要一种简单的方法来累积它们而不必预先分配大面积的内存或执行频繁 reallocations/copies。相反,您只需保留一个块列表,稍后 present as a lazy bytestring. (When list concatenations start getting expensive or the granularity is too small, you can use a Builder 作为进一步优化。)

另一个常见的用例是一些复合数据结构的序列化(比如 aeson 的 Value). If all you are going to do is dump the generated bytes into a file or a network request, it doesn't make much sense to perform a relatively costly consolidation of the serialized bytes of each sub-component. If needed, you can always perform it later with toStrict 无论如何。