Skip to content

Commit 3417e0b

Browse files
committed
http: lazy create IncomingMessage.headers
When rawHeaders is enough don't create the headers object.
1 parent f4586c9 commit 3417e0b

File tree

1 file changed

+50
-6
lines changed

1 file changed

+50
-6
lines changed

lib/_http_incoming.js

Lines changed: 50 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,14 @@
2424
const {
2525
ObjectDefineProperty,
2626
ObjectSetPrototypeOf,
27+
Symbol
2728
} = primordials;
2829

2930
const Stream = require('stream');
3031

32+
const kHeaders = Symbol('kHeaders');
33+
const kTrailers = Symbol('kTrailers');
34+
3135
function readStart(socket) {
3236
if (socket && !socket._paused && socket.readable)
3337
socket.resume();
@@ -58,9 +62,9 @@ function IncomingMessage(socket) {
5862
this.httpVersionMinor = null;
5963
this.httpVersion = null;
6064
this.complete = false;
61-
this.headers = {};
65+
this[kHeaders] = null;
6266
this.rawHeaders = [];
63-
this.trailers = {};
67+
this[kTrailers] = null;
6468
this.rawTrailers = [];
6569

6670
this.aborted = false;
@@ -93,6 +97,44 @@ ObjectDefineProperty(IncomingMessage.prototype, 'connection', {
9397
}
9498
});
9599

100+
ObjectDefineProperty(IncomingMessage.prototype, 'headers', {
101+
get: function() {
102+
if (!this[kHeaders]) {
103+
this[kHeaders] = {};
104+
105+
const src = this.rawHeaders;
106+
const dst = this[kHeaders];
107+
108+
for (let n = 0; n < src.length; n += 2) {
109+
this._addHeaderLine(src[n + 0], src[n + 1], dst);
110+
}
111+
}
112+
return this[kHeaders];
113+
},
114+
set: function(val) {
115+
this[kHeaders] = val;
116+
}
117+
});
118+
119+
ObjectDefineProperty(IncomingMessage.prototype, 'trailers', {
120+
get: function() {
121+
if (!this[kTrailers]) {
122+
this[kTrailers] = {};
123+
124+
const src = this.rawTrailers;
125+
const dst = this[kTrailers];
126+
127+
for (let n = 0; n < src.length; n += 2) {
128+
this._addHeaderLine(src[n + 0], src[n + 1], dst);
129+
}
130+
}
131+
return this[kTrailers];
132+
},
133+
set: function(val) {
134+
this[kTrailers] = val;
135+
}
136+
});
137+
96138
IncomingMessage.prototype.setTimeout = function setTimeout(msecs, callback) {
97139
if (callback)
98140
this.on('timeout', callback);
@@ -133,14 +175,16 @@ function _addHeaderLines(headers, n) {
133175
let dest;
134176
if (this.complete) {
135177
this.rawTrailers = headers;
136-
dest = this.trailers;
178+
dest = this[kTrailers];
137179
} else {
138180
this.rawHeaders = headers;
139-
dest = this.headers;
181+
dest = this[kHeaders];
140182
}
141183

142-
for (let i = 0; i < n; i += 2) {
143-
this._addHeaderLine(headers[i], headers[i + 1], dest);
184+
if (dest) {
185+
for (let i = 0; i < n; i += 2) {
186+
this._addHeaderLine(headers[i], headers[i + 1], dest);
187+
}
144188
}
145189
}
146190
}

0 commit comments

Comments
 (0)