diff --git a/HISTORY.md b/HISTORY.md index ca6f6eb1..573417c6 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -6,6 +6,7 @@ unreleased - deps: mime-db@'>= 1.38.0 < 2' * deps: on-headers@~1.0.2 - Fix `res.writeHead` patch missing return value + * perf: prevent unnecessary buffer copy 1.7.3 / 2018-07-15 ================== diff --git a/index.js b/index.js index f190c689..1d089427 100644 --- a/index.js +++ b/index.js @@ -85,7 +85,7 @@ function compression (options) { } return stream - ? stream.write(Buffer.from(chunk, encoding)) + ? stream.write(toBuffer(chunk, encoding)) : _write.call(this, chunk, encoding) } @@ -112,7 +112,7 @@ function compression (options) { // write Buffer for Node.js 0.8 return chunk - ? stream.end(Buffer.from(chunk, encoding)) + ? stream.end(toBuffer(chunk, encoding)) : stream.end() } @@ -275,3 +275,14 @@ function shouldTransform (req, res) { return !cacheControl || !cacheControlNoTransformRegExp.test(cacheControl) } + +/** + * Coerce arguments to Buffer + * @private + */ + +function toBuffer (chunk, encoding) { + return !Buffer.isBuffer(chunk) + ? Buffer.from(chunk, encoding) + : chunk +}