簡體   English   中英

Javascript / node.js對象,可以存儲任意二進制數據並非常快速地追加

[英]Javascript/node.js Object that can store arbitrary binary data and do appending very fast

我需要在Node.js應用程序中處理大量二進制數據。 當數據通過回調到達我的代碼部分的許多小塊(以Buffer對象的格式)時,我必須每秒執行許多操作,例如追加,切片等。

我很想將二進制數據存儲在Javascript字符串中,該字符串支持追加,切片等。但是不幸的是,我無法真正將(任意)二進制數據轉換為字符串,而字符串必須具有有效的編碼,例如UTF8。

要使用Buffer對象,附加操作將變得非常昂貴。 例如,以下代碼段在我的P7處理器上花費了1.5秒。

var a = new Buffer([1])
var b = new Buffer([2])
var start = new Date()
for (i=0; i<100000; i++) {
a = Buffer.concat([a, b], a.length + 1)
}
console.log(new Date() - start)

如果我在假設a和b是字符串的情況下添加簡單的字符串a += b ,則只需0.01秒。

我想知道Javascript中是否有一個對象可以存儲任意二進制數據並支持非常高效的追加。

提前致謝

UPDATE1

嘗試使用TypeArray,速度要好一些,但仍然比字符串附加要慢得多。

var a = new Uint8Array(),
    b = new Uint8Array(1);
var c
b[0] = 11
var start = new Date()
for (i=0; i<100000; i++) {
    c = new Uint8Array (a.length + b.length)
    c.set(a,0)
    c.set(b, a.length)
    a = c
}

console.log(new Date() - start)
console.log(a.length)

我認為smart-buffer可能就是您想要的? 它允許您將其他緩沖區寫入其中,並將根據需要動態調整大小。

測試腳本:

const SmartBuffer = require('smart-buffer').SmartBuffer;

// set up buffers
var a = new Buffer([1])
var smart_a = new SmartBuffer();
smart_a.writeInt8(1);

var b = new Buffer([2])

// time buffer concatenation method
console.time("Buffer concatenation");
for (let i = 0; i < 100000; i++) {
    a = Buffer.concat([a, b], a.length + 1)
}
console.timeEnd("Buffer concatenation");

// time smart buffer writeBuffer method
console.time("Smart Buffer writing");
for (let i = 0; i < 100000; i++) {
    smart_a.writeBuffer(b);
}
let final_smart_a = smart_a.toBuffer();
console.timeEnd("Smart Buffer writing");

// check that resulting buffers match
for (let i = 0; i < 100000; i++) {
    console.assert(a[i] == final_smart_a[i]);
}

結果(1個試驗):

Buffer concatenation: 2110.282ms
Smart Buffer writing: 14.971ms

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM