推荐的方法来增加缓冲区? [英] Recommended way to grow a Buffer?

查看:143
本文介绍了推荐的方法来增加缓冲区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在Node中构造一个可变长度的字符串或一系列字节。 buf.write的文档说:

Let's say I am constructing a string, or series of bytes, of variable length, in Node. The documentation for buf.write says:

https://nodejs.org/api/buffer.html#buffer_buf_write_string_offset_length_encoding


根据偏移量将字符串写入buf
编码中的字符编码。 length参数是要写入的字节数。如果buf
没有足够的空间来容纳整个字符串,则只会写入部分
的字符串。但是,将不会写入部分编码的
字符。

Writes string to buf at offset according to the character encoding in encoding. The length parameter is the number of bytes to write. If buf did not contain enough space to fit the entire string, only a partial amount of string will be written. However, partially encoded characters will not be written.

比方说,我要写入比缓冲区有更多空间的数据对于。推荐的生长方式是什么?似乎没有 .grow 方法或类似方法。我可以调用 Buffer.from(buf)创建一个新的Buffer,但这似乎效率很低。

Let's say I want to write more data than the Buffer has room for. What is the recommended way to grow it? It doesn't seem like there is a .grow method or similar. I can call Buffer.from(buf) to create a new Buffer, but that seems inefficient.

推荐答案

如果一开始不知道最终大小,则可以使用通常用于动态数组

When the final size is not known at the beginning, you can use the approach typically applied for dynamic arrays:


  1. 分配 Buffer 大小

  2. 将内容写入缓冲区,只要有空间

  3. 当下一块内容不能容纳,创建一个新的 Buffer ,其大小增加一倍,将旧缓冲区的内容复制到新缓冲区中,然后像以前一样将新内容写入末尾

  1. allocate Buffer with some initial size
  2. write content to Buffer as long as there is space
  3. when the next piece of content cannot fit, create a new Buffer with double the size, copy old buffer's content to the new buffer, and write the new content to the end as before

这样,可以在 O(1)中摊销缓冲区的末尾插入时间。

That way inserting at the end of the buffer can be performed in O(1) amortized time.

这种方法的变体通常用于 Java ,.NET或例如.NET的 MemoryStream 中,它对应于nodejs Buffer 。您可以看到如何实现 MemoryStream -此处

Variants of this approach are commonly used in resizable lists in Java, .NET, or e.g. in .NET's MemoryStream which corresponds to nodejs Buffer. You can see how MemoryStream is implemented - here.

大小不一定必须加倍。您可以选择其他指数,例如 3/2 ,如果您想节省一些空间。

Size does not necessarily have to be doubled. You can choose a different exponent, e.g. 3/2, if you want to save some space.

当然,最佳方法取决于您用例,但总体来说效果不错。

Of course what is the best approach depends on your use case, but this one performs well in general.

这篇关于推荐的方法来增加缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆