穩(wěn)定性: 1 - 試驗(yàn)
由簡(jiǎn)單內(nèi)存分配器(處理擴(kuò)展原始內(nèi)存的分配)支持的緩存。Smalloc 有以下函數(shù):
length {Number} <= smalloc.kMaxLengthreceiver {Object} 默認(rèn): new Objecttype {Enum} 默認(rèn): Uint8返回 receiver 對(duì)象,包含分配的外部數(shù)組數(shù)據(jù)。如果沒有傳入receiver ,將會(huì)創(chuàng)建并返回一個(gè)新的對(duì)象。
這可用于創(chuàng)建你自己的類似 buffer 的類。不會(huì)設(shè)置其他屬性,因此使用者需要跟蹤其他所需信息(比如分配的長(zhǎng)度)。
function SimpleData(n) {
this.length = n;
smalloc.alloc(this.length, this);
}
SimpleData.prototype = { /* ... */ };
僅檢查 receiver 是否是非數(shù)組的對(duì)象。因此,可以分配擴(kuò)展數(shù)據(jù)數(shù)據(jù),不僅是普通對(duì)象。
function allocMe() { }
smalloc.alloc(3, allocMe);
// { [Function allocMe] '0': 0, '1': 0, '2': 0 }
v8 不支持給數(shù)組分配擴(kuò)展數(shù)組對(duì)象,如果這么做,將會(huì)拋出。
你可以指定外部數(shù)組數(shù)據(jù)的類型。所有可用類型在 smalloc.Types 列出,例如:
var doubleArr = smalloc.alloc(3, smalloc.Types.Double);
for (var i = 0; i < 3; i++)
doubleArr = i / 10;
// { '0': 0, '1': 0.1, '2': 0.2 }
使用 Object.freeze, Object.seal 和 Object.preventExtensions不能凍結(jié),封鎖,阻止對(duì)象的使用擴(kuò)展數(shù)據(jù)擴(kuò)展。
source {Object} 分配了外部數(shù)組的對(duì)象sourceStart {Number} 負(fù)責(zé)的起始位置dest {Object} 分配了外部數(shù)組的對(duì)象destStart {Number} 拷貝到目標(biāo)的起始位置copyLength {Number} 需要拷貝的長(zhǎng)度從一個(gè)外部數(shù)組拷貝內(nèi)存到另外一個(gè),所有的參數(shù)都必填,否則會(huì)拋出異常。
var a = smalloc.alloc(4);
var b = smalloc.alloc(4);
for (var i = 0; i < 4; i++) {
a[i] = i;
b[i] = i * 2;
}
// { '0': 0, '1': 1, '2': 2, '3': 3 }
// { '0': 0, '1': 2, '2': 4, '3': 6 }
smalloc.copyOnto(b, 2, a, 0, 2);
// { '0': 4, '1': 6, '2': 2, '3': 3 }
copyOnto 會(huì)在內(nèi)部自動(dòng)檢測(cè)分配的長(zhǎng)度,因此不必設(shè)置任何附加參數(shù)。
obj Object釋放通過(guò) smalloc.alloc 給對(duì)象分配的內(nèi)存。
var a = {};
smalloc.alloc(3, a);
// { '0': 0, '1': 0, '2': 0 }
smalloc.dispose(a);
// {}
有利于減輕垃圾回收器的負(fù)擔(dān),但是開發(fā)時(shí)候還是要小心。程序里可能會(huì)出現(xiàn)難以跟蹤的錯(cuò)誤。
var a = smalloc.alloc(4);
var b = smalloc.alloc(4);
// perform this somewhere along the line
smalloc.dispose(b);
// now trying to copy some data out
smalloc.copyOnto(b, 2, a, 0, 2);
// now results in:
// RangeError: copy_length > source_length
調(diào)用 dispose() ,對(duì)象依舊擁有外部數(shù)據(jù),例如 smalloc.hasExternalData() 會(huì)返回 true。dispose()不支持緩存,如果傳入將會(huì)拋出。
obj {Object}如果 obj擁有外部分配的內(nèi)存,返回true。
可分配的最大數(shù)量。同樣適用于緩存創(chuàng)建。
外部數(shù)組的類型,包含:
Int8Uint8Int16Uint16Int32Uint32FloatDoubleUint8Clamped