Skip to content

Commit

Permalink
fixup! lib: revert primordials in a hot path
Browse files Browse the repository at this point in the history
  • Loading branch information
aduh95 committed Apr 16, 2021
1 parent ed49b52 commit 39292b9
Show file tree
Hide file tree
Showing 17 changed files with 138 additions and 167 deletions.
3 changes: 1 addition & 2 deletions lib/_http_common.js
Expand Up @@ -22,7 +22,6 @@
'use strict';

const {
ArrayPrototypePushApply,
MathMin,
Symbol,
RegExpPrototypeTest,
Expand Down Expand Up @@ -65,7 +64,7 @@ function parserOnHeaders(headers, url) {
// Once we exceeded headers limit - stop collecting them
if (this.maxHeaderPairs <= 0 ||
this._headers.length < this.maxHeaderPairs) {
ArrayPrototypePushApply(this._headers, headers);
this._headers.push(...headers);
}
this._url += url;
}
Expand Down
3 changes: 1 addition & 2 deletions lib/_http_incoming.js
Expand Up @@ -22,7 +22,6 @@
'use strict';

const {
ArrayPrototypePush,
ObjectDefineProperty,
ObjectSetPrototypeOf,
StringPrototypeCharCodeAt,
Expand Down Expand Up @@ -349,7 +348,7 @@ function _addHeaderLine(field, value, dest) {
} else if (flag === 1) {
// Array header -- only Set-Cookie at the moment
if (dest['set-cookie'] !== undefined) {
ArrayPrototypePush(dest['set-cookie'], value);
dest['set-cookie'].push(value);
} else {
dest['set-cookie'] = [value];
}
Expand Down
14 changes: 6 additions & 8 deletions lib/_http_outgoing.js
Expand Up @@ -24,10 +24,7 @@
const {
Array,
ArrayIsArray,
ArrayPrototypeForEach,
ArrayPrototypeJoin,
ArrayPrototypePush,
ArrayPrototypeUnshift,
MathFloor,
NumberPrototypeToString,
ObjectCreate,
Expand Down Expand Up @@ -328,7 +325,7 @@ OutgoingMessage.prototype._send = function _send(data, encoding, callback) {
data = this._header + data;
} else {
const header = this._header;
ArrayPrototypeUnshift(this.outputData, {
this.outputData.unshift({
data: header,
encoding: 'latin1',
callback: null
Expand Down Expand Up @@ -365,7 +362,7 @@ function _writeRaw(data, encoding, callback) {
return conn.write(data, encoding, callback);
}
// Buffer, as long as we're not destroyed.
ArrayPrototypePush(this.outputData, { data, encoding, callback });
this.outputData.push({ data, encoding, callback });
this.outputSize += data.length;
this._onPendingData(data.length);
return this.outputSize < HIGH_WATER_MARK;
Expand Down Expand Up @@ -394,9 +391,10 @@ function _storeHeader(firstLine, headers) {
}
} else if (ArrayIsArray(headers)) {
if (headers.length && ArrayIsArray(headers[0])) {
ArrayPrototypeForEach(headers, (entry) =>
processHeader(this, state, entry[0], entry[1], true)
);
for (let i = 0; i < headers.length; i++) {
const entry = headers[i];
processHeader(this, state, entry[0], entry[1], true);
}
} else {
if (headers.length % 2 !== 0) {
throw new ERR_INVALID_ARG_VALUE('headers', headers);
Expand Down
37 changes: 17 additions & 20 deletions lib/_http_server.js
Expand Up @@ -23,14 +23,9 @@

const {
ArrayIsArray,
ArrayPrototypeForEach,
ArrayPrototypePush,
ArrayPrototypeShift,
Error,
FunctionPrototypeCall,
ObjectKeys,
ObjectSetPrototypeOf,
ReflectApply,
RegExpPrototypeTest,
Symbol,
SymbolFor,
Expand Down Expand Up @@ -209,7 +204,7 @@ ObjectSetPrototypeOf(ServerResponse, OutgoingMessage);
ServerResponse.prototype._finish = function _finish() {
DTRACE_HTTP_SERVER_RESPONSE(this.socket);
emitStatistics(this[kServerResponseStatistics]);
FunctionPrototypeCall(OutgoingMessage.prototype._finish, this);
OutgoingMessage.prototype._finish.call(this);
};


Expand Down Expand Up @@ -419,17 +414,19 @@ Server.prototype[EE.captureRejectionSymbol] = function(err, event, ...args) {
const { 1: res } = args;
if (!res.headersSent && !res.writableEnded) {
// Don't leak headers.
ArrayPrototypeForEach(res.getHeaderNames(),
(name) => res.removeHeader(name));
const names = res.getHeaderNames();
for (let i = 0; i < names.length; i++) {
res.removeHeader(names[i]);
}
res.statusCode = 500;
res.end(STATUS_CODES[500]);
} else {
res.destroy();
}
break;
default:
ReflectApply(net.Server.prototype[SymbolFor('nodejs.rejection')],
this, arguments);
net.Server.prototype[SymbolFor('nodejs.rejection')]
.apply(this, arguments);
}
};

Expand Down Expand Up @@ -591,7 +588,7 @@ function socketOnClose(socket, state) {

function abortIncoming(incoming) {
while (incoming.length) {
const req = ArrayPrototypeShift(incoming);
const req = incoming.shift();
req.destroy(connResetException('aborted'));
}
// Abort socket._httpMessage ?
Expand All @@ -603,7 +600,7 @@ function socketOnEnd(server, socket, parser, state) {
if (ret instanceof Error) {
debug('parse error');
// socketOnError has additional logic and will call socket.destroy(err).
FunctionPrototypeCall(socketOnError, socket, ret);
socketOnError.call(socket, ret);
} else if (!server.httpAllowHalfOpen) {
socket.end();
} else if (state.outgoing.length) {
Expand All @@ -626,7 +623,7 @@ function socketOnData(server, socket, parser, state, d) {
function onRequestTimeout(socket) {
socket[kRequestTimeout] = undefined;
// socketOnError has additional logic and will call socket.destroy(err).
FunctionPrototypeCall(socketOnError, socket, new ERR_HTTP_REQUEST_TIMEOUT());
socketOnError.call(socket, new ERR_HTTP_REQUEST_TIMEOUT());
}

function onParserExecute(server, socket, parser, state, ret) {
Expand Down Expand Up @@ -693,7 +690,7 @@ function onParserExecuteCommon(server, socket, parser, state, ret, d) {
prepareError(ret, parser, d);
ret.rawPacket = d || parser.getCurrentBuffer();
debug('parse error', ret);
FunctionPrototypeCall(socketOnError, socket, ret);
socketOnError.call(socket, ret);
} else if (parser.incoming && parser.incoming.upgrade) {
// Upgrade or CONNECT
const req = parser.incoming;
Expand Down Expand Up @@ -799,7 +796,7 @@ function resOnFinish(req, res, socket, state, server) {
// array will be empty.
assert(state.incoming.length === 0 || state.incoming[0] === req);

ArrayPrototypeShift(state.incoming);
state.incoming.shift();

// If the user never called req.read(), and didn't pipe() or
// .resume() or .on('data'), then we call req._dump() so that the
Expand Down Expand Up @@ -832,7 +829,7 @@ function resOnFinish(req, res, socket, state, server) {
}
} else {
// Start sending the next message
const m = ArrayPrototypeShift(state.outgoing);
const m = state.outgoing.shift();
if (m) {
m.assignSocket(socket);
}
Expand All @@ -858,7 +855,7 @@ function parserOnIncoming(server, socket, state, req, keepAlive) {
return 2;
}

ArrayPrototypePush(state.incoming, req);
state.incoming.push(req);

// If the writable end isn't consuming, then stop reading
// so that we don't become overwhelmed by a flood of
Expand Down Expand Up @@ -893,7 +890,7 @@ function parserOnIncoming(server, socket, state, req, keepAlive) {

if (socket._httpMessage) {
// There are already pending outgoing res, append.
ArrayPrototypePush(state.outgoing, res);
state.outgoing.push(res);
} else {
res.assignSocket(socket);
}
Expand Down Expand Up @@ -974,8 +971,8 @@ function unconsume(parser, socket) {

function generateSocketListenerWrapper(originalFnName) {
return function socketListenerWrap(ev, fn) {
const res = ReflectApply(net.Socket.prototype[originalFnName], this,
[ev, fn]);
const res = net.Socket.prototype[originalFnName].call(this,
ev, fn);
if (!this.parser) {
this.on = net.Socket.prototype.on;
this.addListener = net.Socket.prototype.addListener;
Expand Down
21 changes: 9 additions & 12 deletions lib/events.js
Expand Up @@ -22,13 +22,10 @@
'use strict';

const {
ArrayPrototypeForEach,
ArrayPrototypePush,
ArrayPrototypeSlice,
Boolean,
Error,
ErrorCaptureStackTrace,
FunctionPrototypeCall,
MathMin,
NumberIsNaN,
ObjectCreate,
Expand All @@ -39,7 +36,6 @@ const {
Promise,
PromiseReject,
PromiseResolve,
ReflectApply,
ReflectOwnKeys,
String,
Symbol,
Expand Down Expand Up @@ -166,7 +162,8 @@ EventEmitter.setMaxListeners =
isEventTarget = require('internal/event_target').isEventTarget;

// Performance for forEach is now comparable with regular for-loop
ArrayPrototypeForEach(eventTargets, (target) => {
for (let i = 0; i < eventTargets.length; i++) {
const target = eventTargets[i];
if (isEventTarget(target)) {
target[kMaxEventTargetListeners] = n;
target[kMaxEventTargetListenersWarned] = false;
Expand All @@ -178,7 +175,7 @@ EventEmitter.setMaxListeners =
['EventEmitter', 'EventTarget'],
target);
}
});
}
}
};

Expand Down Expand Up @@ -217,7 +214,7 @@ function addCatch(that, promise, type, args) {
const then = promise.then;

if (typeof then === 'function') {
FunctionPrototypeCall(then, promise, undefined, function(err) {
then.call(promise, undefined, function(err) {
// The callback is called with nextTick to avoid a follow-up
// rejection from this promise.
process.nextTick(emitUnhandledRejectionOrErr, that, err, type, args);
Expand Down Expand Up @@ -366,7 +363,7 @@ EventEmitter.prototype.emit = function emit(type, ...args) {
return false;

if (typeof handler === 'function') {
const result = ReflectApply(handler, this, args);
const result = handler.apply(this, args);

// We check if result is undefined first because that
// is the most common case so we do not pay any perf
Expand All @@ -378,7 +375,7 @@ EventEmitter.prototype.emit = function emit(type, ...args) {
const len = handler.length;
const listeners = arrayClone(handler);
for (let i = 0; i < len; ++i) {
const result = ReflectApply(listeners[i], this, args);
const result = listeners[i].apply(this, args);

// We check if result is undefined first because that
// is the most common case so we do not pay any perf
Expand Down Expand Up @@ -690,7 +687,7 @@ function getEventListeners(emitterOrTarget, type) {
while (handler?.listener !== undefined) {
const listener = handler.listener?.deref ?
handler.listener.deref() : handler.listener;
ArrayPrototypePush(listeners, listener);
listeners.push(listener);
handler = handler.next;
}
return listeners;
Expand Down Expand Up @@ -807,7 +804,7 @@ function on(emitter, event, options) {

// Wait until an event happens
return new Promise(function(resolve, reject) {
ArrayPrototypePush(unconsumedPromises, { resolve, reject });
unconsumedPromises.push({ resolve, reject });
});
},

Expand Down Expand Up @@ -871,7 +868,7 @@ function on(emitter, event, options) {
if (promise) {
promise.resolve(createIterResult(args, false));
} else {
ArrayPrototypePush(unconsumedEvents, args);
unconsumedEvents.push(args);
}
}

Expand Down
17 changes: 7 additions & 10 deletions lib/internal/async_hooks.js
@@ -1,14 +1,11 @@
'use strict';

const {
ArrayPrototypePop,
ArrayPrototypeSlice,
ArrayPrototypeUnshift,
ErrorCaptureStackTrace,
ObjectPrototypeHasOwnProperty,
ObjectDefineProperty,
Promise,
ReflectApply,
Symbol,
} = primordials;

Expand Down Expand Up @@ -128,16 +125,16 @@ function callbackTrampoline(asyncId, resource, cb, ...args) {

let result;
if (asyncId === 0 && typeof domain_cb === 'function') {
ArrayPrototypeUnshift(args, cb);
result = ReflectApply(domain_cb, this, args);
args.unshift(cb);
result = domain_cb.apply(this, args);
} else {
result = ReflectApply(cb, this, args);
result = cb.apply(this, args);
}

if (asyncId !== 0 && hasHooks(kAfter))
emitAfterNative(asyncId);

ArrayPrototypePop(execution_async_resources);
execution_async_resources.pop();
return result;
}

Expand Down Expand Up @@ -428,14 +425,14 @@ function clearDefaultTriggerAsyncId() {

function defaultTriggerAsyncIdScope(triggerAsyncId, block, ...args) {
if (triggerAsyncId === undefined)
return ReflectApply(block, null, args);
return block.apply(null, args);
// CHECK(NumberIsSafeInteger(triggerAsyncId))
// CHECK(triggerAsyncId > 0)
const oldDefaultTriggerAsyncId = async_id_fields[kDefaultTriggerAsyncId];
async_id_fields[kDefaultTriggerAsyncId] = triggerAsyncId;

try {
return ReflectApply(block, null, args);
return block.apply(null, args);
} finally {
async_id_fields[kDefaultTriggerAsyncId] = oldDefaultTriggerAsyncId;
}
Expand Down Expand Up @@ -532,7 +529,7 @@ function popAsyncContext(asyncId) {
const offset = stackLength - 1;
async_id_fields[kExecutionAsyncId] = async_wrap.async_ids_stack[2 * offset];
async_id_fields[kTriggerAsyncId] = async_wrap.async_ids_stack[2 * offset + 1];
ArrayPrototypePop(execution_async_resources);
execution_async_resources.pop();
async_hook_fields[kStackLength] = offset;
return offset > 0;
}
Expand Down
7 changes: 2 additions & 5 deletions lib/internal/streams/destroy.js
Expand Up @@ -7,7 +7,6 @@ const {
},
} = require('internal/errors');
const {
FunctionPrototypeCall,
Symbol,
} = primordials;

Expand Down Expand Up @@ -99,8 +98,7 @@ function _destroy(self, err, cb) {
try {
const then = result.then;
if (typeof then === 'function') {
FunctionPrototypeCall(
then,
then.call(
result,
function() {
if (called)
Expand Down Expand Up @@ -318,8 +316,7 @@ function constructNT(stream) {
try {
const then = result.then;
if (typeof then === 'function') {
FunctionPrototypeCall(
then,
then.call(
result,
function() {
// If the callback was invoked, do nothing further.
Expand Down

0 comments on commit 39292b9

Please sign in to comment.