靜態方法:Buffer.allocUnsafeSlow(size)
曆史
| 版本 | 變化 |
|---|---|
| v15.0.0 | 對於無效的輸入參數,拋出 ERR_INVALID_ARG_VALUE 而不是 ERR_INVALID_OPT_VALUE。 |
| v5.12.0 | 添加於:v5.12.0 |
參數
size<integer> 新Buffer的所需長度。
分配 size 字節的新 Buffer。如果size大於 或小於0,則拋出buffer.constants.MAX_LENGTH 。如果 ERR_INVALID_ARG_VALUE size 為 0,則創建零長度 Buffer。
以這種方式創建的Buffer 實例的底層內存未初始化。新創建的Buffer 的內容未知,可能包含敏感數據。使用 將此類 buf.fill(0) Buffer 實例初始化為零。
當使用 分配新的 Buffer.allocUnsafe() Buffer 實例時,4 KiB 下的分配是從單個預分配的 Buffer 中分割出來的。這允許應用程序避免創建許多單獨分配的Buffer 實例的垃圾收集開銷。這種方法無需跟蹤和清理盡可能多的單個ArrayBuffer 對象,從而提高了性能和內存使用率。
但是,在開發人員可能需要在不確定的時間內從池中保留一小塊內存的情況下,使用 Buffer.allocUnsafeSlow() 創建 un-pooled Buffer 實例然後複製出相關位。
import { Buffer } from 'node:buffer'; // Need to keep around a few small chunks of memory. const store = []; socket.on('readable', () => { let data; while (null !== (data = readable.read())) { // Allocate for retained data. const sb = Buffer.allocUnsafeSlow(10); // Copy the data into the new allocation. data.copy(sb, 0, 0, 10); store.push(sb); } });const { Buffer } = require('node:buffer'); // Need to keep around a few small chunks of memory. const store = []; socket.on('readable', () => { let data; while (null !== (data = readable.read())) { // Allocate for retained data. const sb = Buffer.allocUnsafeSlow(10); // Copy the data into the new allocation. data.copy(sb, 0, 0, 10); store.push(sb); } });
如果 size 不是數字,則會拋出 TypeError。
相關用法
- Node.js Buffer.allocUnsafeSlow()用法及代碼示例
- Node.js Buffer.allocUnsafe()用法及代碼示例
- Node.js Buffer.allocUnsafe(size)用法及代碼示例
- Node.js Buffer.alloc(size[, fill[, encoding]])用法及代碼示例
- Node.js Buffer.alloc()用法及代碼示例
- Node.js Buffer.fill()用法及代碼示例
- Node.js Buffer.writeInt16BE()用法及代碼示例
- Node.js Buffer.writeDoubleBE()用法及代碼示例
- Node.js Buffer.entries()用法及代碼示例
- Node.js Buffer.writeUInt16LE()用法及代碼示例
- Node.js Buffer.byteLength()用法及代碼示例
- Node.js Buffer.isBuffer()用法及代碼示例
- Node.js Buffer.writeUInt32BE()用法及代碼示例
- Node.js Buffer.equals()用法及代碼示例
- Node.js Buffer.values()用法及代碼示例
- Node.js Buffer.isEncoding()用法及代碼示例
- Node.js Buffer.isEncoding(encoding)用法及代碼示例
- Node.js Buffer.concat(list[, totalLength])用法及代碼示例
- Node.js Buffer.subarray()用法及代碼示例
- Node.js Buffer.writeDoubleLE()用法及代碼示例
- Node.js Buffer.includes()用法及代碼示例
- Node.js Buffer.readInt32BE()用法及代碼示例
- Node.js Buffer.writeIntLE()用法及代碼示例
- Node.js Buffer.from(array)用法及代碼示例
- Node.js Buffer.swap16()用法及代碼示例
注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 Buffer.allocUnsafeSlow(size)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
