这是 实验性技术
检查 浏览器兼容性表格 要小心谨慎在生产中使用这之前。

静态 ArrayBuffer.transfer() method returns a new ArrayBuffer whose contents have been taken from the oldBuffer 's data and then is either truncated or zero-extended by newByteLength 。若 newByteLength is undefined byteLength of the oldBuffer is used. This operation leaves oldBuffer in a detached state.

句法

ArrayBuffer.transfer(oldBuffer [, newByteLength]);
					

参数

oldBuffer
ArrayBuffer object from which to transfer.
newByteLength
The byte length of the new ArrayBuffer 对象。

返回值

A new ArrayBuffer 对象。

描述

ArrayBuffer.transfer() method allows you to grow and detach ArrayBuffer objects. The ability to grow an ArrayBuffer without copying has the advantage of being much faster for large buffers (similar to realloc). The ability to detach an ArrayBuffer gives the developer explicit control over when the underlying memory is released.  This avoids having to drop all references and wait for garbage collection.

范例

var buf1 = new ArrayBuffer(40);
new Int32Array(buf1)[0] = 42;
var buf2 = ArrayBuffer.transfer(buf1, 80);
buf1.byteLength; // 0 but if you use the polyfill then the value is still 40
buf2.byteLength; // 80
new Int32Array(buf2)[0]; // 42
var buf3 = ArrayBuffer.transfer(buf2, 0);
buf2.byteLength; // 0 but if you use the polyfill then the value is still 80
buf3.byteLength; // 0
					

Polyfill

You can partially work around this by inserting the following code at the beginning of your scripts, allowing use of much of the functionality of transfer () in browsers that do not natively support it. This is not the exact equivalent of this API because browsers that natively support it are be able to internally use the C++ function realloc() which extends the length of the memory and only copies it to a new location as-needed as opposed to the following pollyfill which always copies the whole thing to a new space of memory, but this function transfers data from one ArrayBuffer to another ArrayBuffer.

if (!ArrayBuffer.transfer) {
    ArrayBuffer.transfer = function(source, length) {
        if (!(source instanceof ArrayBuffer))
            throw new TypeError('Source must be an instance of ArrayBuffer');
        if (length <= source.byteLength)
            return source.slice(0, length);
        var sourceView = new Uint8Array(source),
            destView = new Uint8Array(new ArrayBuffer(length));
        destView.set(sourceView);
        return destView.buffer;
    };
}
					

规范

规范 状态 注释
ArrayBuffer.prototype.transfer proposal 草案 Stage 2 Draft

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

No compatibility data found. Please contribute data for "javascript.builtins.ArrayBuffer.transfer" (depth: 1) to the MDN 兼容性数据存储库 .

另请参阅

元数据

  • 最后修改: