Skip to content

Commit b43205c

Browse files
committed
perf: prevent multiple Buffer creation in res.send
1 parent 112dbb2 commit b43205c

File tree

3 files changed

+24
-10
lines changed

3 files changed

+24
-10
lines changed

History.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
unreleased
2+
==========
3+
4+
* perf: prevent multiple `Buffer` creation in `res.send`
5+
16
4.6.1 / 2014-07-12
27
==================
38

lib/response.js

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -145,17 +145,24 @@ res.send = function send(body) {
145145
}
146146

147147
// populate Content-Length
148-
if (chunk !== undefined && !this.get('Content-Length')) {
149-
len = Buffer.isBuffer(chunk)
150-
? chunk.length
151-
: Buffer.byteLength(chunk, encoding);
148+
if (chunk !== undefined) {
149+
if (!Buffer.isBuffer(chunk)) {
150+
// convert chunk to Buffer; saves later double conversions
151+
chunk = new Buffer(chunk, encoding);
152+
encoding = undefined;
153+
}
154+
155+
len = chunk.length;
152156
this.set('Content-Length', len);
153157
}
154158

159+
// method check
160+
var isHead = req.method === 'HEAD';
161+
155162
// ETag support
156-
var etag = len !== undefined && app.get('etag fn');
157-
if (etag && ('GET' === req.method || 'HEAD' === req.method)) {
158-
if (!this.get('ETag')) {
163+
if (len !== undefined && (isHead || req.method === 'GET')) {
164+
var etag = app.get('etag fn');
165+
if (etag && !this.get('ETag')) {
159166
etag = etag(chunk, encoding);
160167
etag && this.set('ETag', etag);
161168
}
@@ -173,7 +180,7 @@ res.send = function send(body) {
173180
}
174181

175182
// skip body for HEAD
176-
if (req.method === 'HEAD') {
183+
if (isHead) {
177184
this.end();
178185
}
179186

test/res.send.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -512,8 +512,10 @@ describe('res', function(){
512512
var app = express()
513513

514514
app.set('etag', function(body, encoding){
515-
body.should.equal('hello, world!')
516-
encoding.should.equal('utf8')
515+
var chunk = !Buffer.isBuffer(body)
516+
? new Buffer(body, encoding)
517+
: body;
518+
chunk.toString().should.equal('hello, world!')
517519
return '"custom"'
518520
});
519521

0 commit comments

Comments
 (0)