diff --git a/History.md b/History.md index 765f050318..83ba2cc5d7 100644 --- a/History.md +++ b/History.md @@ -2,6 +2,7 @@ unreleased ========== * Improve error message when autoloading invalid view engine + * Skip `Buffer` encoding when not generating ETag for small response 4.15.5 / 2017-09-24 =================== diff --git a/lib/response.js b/lib/response.js index b852a60e2f..e34af49d69 100644 --- a/lib/response.js +++ b/lib/response.js @@ -106,7 +106,6 @@ res.links = function(links){ res.send = function send(body) { var chunk = body; var encoding; - var len; var req = this.req; var type; @@ -171,23 +170,33 @@ res.send = function send(body) { } } + // determine if ETag should be generated + var etagFn = app.get('etag fn') + var generateETag = !this.get('ETag') && typeof etagFn === 'function' + // populate Content-Length + var len if (chunk !== undefined) { - if (!Buffer.isBuffer(chunk)) { - // convert chunk to Buffer; saves later double conversions + if (!generateETag && chunk.length < 1000) { + // just calculate length when no ETag + small chunk + len = Buffer.byteLength(chunk, encoding) + } else if (!Buffer.isBuffer(chunk)) { + // convert chunk to Buffer and calculate chunk = new Buffer(chunk, encoding); encoding = undefined; + len = chunk.length + } else { + // get length of Buffer + len = chunk.length } - len = chunk.length; this.set('Content-Length', len); } // populate ETag var etag; - var generateETag = len !== undefined && app.get('etag fn'); - if (typeof generateETag === 'function' && !this.get('ETag')) { - if ((etag = generateETag(chunk, encoding))) { + if (generateETag && len !== undefined) { + if ((etag = etagFn(chunk, encoding))) { this.set('ETag', etag); } }