PDF版 ePub版

# Smalloc

稳定性: 1 - 试验

## 类: smalloc

• length {Number} <= smalloc.kMaxLength
• receiver {Object} 默认: new Object
• type {Enum} 默认: Uint8

function SimpleData(n) {
this.length = n;
smalloc.alloc(this.length, this);
}

SimpleData.prototype = { /* ... */ };

function allocMe() { }
smalloc.alloc(3, allocMe);

// { [Function allocMe] '0': 0, '1': 0, '2': 0 }

v8 不支持给数组分配扩展数组对象，如果这么做，将会抛出。

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 }

### smalloc.copyOnto(source, sourceStart, dest, destStart, copyLength);

• source {Object} 分配了外部数组的对象
• sourceStart {Number} 负责的起始位置
• dest {Object} 分配了外部数组的对象
• destStart {Number} 拷贝到目标的起始位置
• copyLength {Number} 需要拷贝的长度

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 会在内部自动检测分配的长度，因此不必设置任何附加参数。

### smalloc.dispose(obj)

• obj Object

var a = {};
smalloc.alloc(3, a);

// { '0': 0, '1': 0, '2': 0 }

smalloc.dispose(a);

// {}

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

### smalloc.hasExternalData(obj)

• obj {Object}

### smalloc.Types

• Int8
• Uint8
• Int16
• Uint16
• Int32
• Uint32
• Float
• Double
• Uint8Clamped