Buffer 使用场景

104 阅读1分钟

Buffer是否提高性能?

代码

const http = require("http");

let hello = "";
for (let i = 0; i < 10240; i++) {
  hello += "a";
}

// console.log(`Hello:${hello.length}`);
// hello = Buffer.from(hello);

http
  .createServer((req, res) => {
    res.writeHead(200);
    res.end(hello);
  })
  .listen(8001);

  1. 使用ab -c 100 -n 18000 http://localhost:8001/测试

    1. 服务器接口返回字符串的时候,qps如下图

    1. 当使用Buffer的时候,qps如下

 3.    目前看两者性能差不多,因为这里都是取的最大值

使用场景

1. I/O操作

const fs = require('fs');

const inputStream = fs.createReadStream('input.txt'); // 创建可读流
const outputStream = fs.createWriteStream('output.txt'); // 创建可写流

inputStream.pipe(outputStream); 

比如 文件的上传和下载还有下载电影时可以边下载边看

在 Stream 中我们是不需要手动去创建自己的缓冲区,在 Node.js 的流中将会自动创建

2. 加密和解密

crypto.createCipheriv(algorithm, key, iv[, options])

3. zlib中使用Buffer

zlib.js 为 Node.js 的核心库之一,其利用了缓冲区(Buffer)的功能来操作二进制数据流,提供了压缩或解压功能

// 连接Buffer
function zlibBufferOnData(chunk) {
  if (!this.buffers)
    this.buffers = [chunk];
  else
    ArrayPrototypePush(this.buffers, chunk);
  this.nread += chunk.length;
  if (this.nread > this._maxOutputLength) {
    this.close();
    this.removeAllListeners('end');
    this.cb(new ERR_BUFFER_TOO_LARGE(this._maxOutputLength));
  }
}