简体   繁体   English

JS:未知大小的ArrayBuffer

[英]JS: ArrayBuffer of Unknown Size

I have a big object that I want to store in an ArrayBuffer (let say Uint8Array). 我有一个大对象,我想存储在ArrayBuffer中(比如说Uint8Array)。 Note: I do not know how big the object is. 注意:我不知道对象有多大。

I already have all the logic about setting the values in the buffer. 我已经拥有了关于在缓冲区中设置值的所有逻辑。 (It is already working if I use new Uint8Array(100000000); for example.) (如果我使用new Uint8Array(100000000);它已经工作了new Uint8Array(100000000);例如。)

The problem is that I don't know if resizing a buffer efficiently is possible. 问题是我不知道是否可以有效地调整缓冲区大小。 Performance is the main preoccupation here. 表演是这里的主要关注点。

I've been thinking starting with let say new Uint8Array(100); 我一直在想开始说new Uint8Array(100); and if I need more, I create a new one with double the size new Uint8Array(200); 如果我需要更多,我创建一个new Uint8Array(200);大小的new Uint8Array(200); and copy the existing content on the new one (not quite sure how). 并复制新的内容(不太确定如何)。 And so on. 等等。

What about just creating a regular array and converting it at the end into a Uint8Array ? 如何创建一个常规数组并将其最终转换为Uint8Array呢?

If you need only one at a time but still many per time and have a need for speed, you need to keep the first array and overwrite it. 如果您一次只需要一个但每次仍然需要很多并且需要速度,则需要保留第一个阵列并覆盖它。 You can work out the amount of memory you need for the first one as you described (it is not that slow) but keep the array for the next ones (you'll need something to keep the current length). 你可以计算你所描述的第一个所需的内存量(它不是那么慢),但保留数组用于下一个(你需要一些东西来保持当前的长度)。 Every time you need more, you do as you did with the first one. 每当您需要更多时,您就像第一个那样做。 You might want to "free" the memory from time to time when it gets too large. 当它变得太大时,你可能想要“释放”内存。

It is a poor-man's malloc() / garbage collector, yes, and it assumes that your need of arrays is strictly consecutive. 它是一个穷人的malloc() /垃圾收集器,是的,并且它假设您对数组的需求是严格连续的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM