perf: partially replace .concat with .push (#13609)

This commit is contained in:
Federico Ciardi 2021-08-14 16:57:06 +02:00 committed by GitHub
parent 6a651e4641
commit 10640b2aad
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 93 additions and 74 deletions

View File

@ -10,7 +10,11 @@ function collect(
const values = value.split(","); const values = value.split(",");
return previousValue ? previousValue.concat(values) : values; if (previousValue) {
previousValue.push(...values);
return previousValue;
}
return values;
} }
commander.option( commander.option(

View File

@ -192,7 +192,8 @@ export default function parseArgv(args: Array<string>): CmdOptions | null {
let filenames = commander.args.reduce(function (globbed, input) { let filenames = commander.args.reduce(function (globbed, input) {
let files = glob.sync(input); let files = glob.sync(input);
if (!files.length) files = [input]; if (!files.length) files = [input];
return globbed.concat(files); globbed.push(...files);
return globbed;
}, []); }, []);
filenames = Array.from(new Set(filenames)); filenames = Array.from(new Set(filenames));
@ -353,5 +354,9 @@ function collect(
const values = value.split(","); const values = value.split(",");
return previousValue ? previousValue.concat(values) : values; if (previousValue) {
previousValue.push(...values);
return previousValue;
}
return values;
} }

View File

@ -42,8 +42,8 @@ export function push(
if (node.decorators) { if (node.decorators) {
const decorators = (map.decorators = const decorators = (map.decorators =
map.decorators || t.arrayExpression([])); map.decorators || t.arrayExpression([]));
decorators.elements = decorators.elements.concat( decorators.elements.push(
node.decorators.map(dec => dec.expression).reverse(), ...node.decorators.map(dec => dec.expression).reverse(),
); );
} }

View File

@ -316,7 +316,7 @@ helpers.extends = helper("7.0.0-beta.0")`
} }
`; `;
// This old helper can be removed in babel v8 // TODO(babel-8): This old helper can be removed in babel v8
helpers.objectSpread = helper("7.0.0-beta.0")` helpers.objectSpread = helper("7.0.0-beta.0")`
import defineProperty from "defineProperty"; import defineProperty from "defineProperty";
@ -325,7 +325,7 @@ helpers.objectSpread = helper("7.0.0-beta.0")`
var source = (arguments[i] != null) ? Object(arguments[i]) : {}; var source = (arguments[i] != null) ? Object(arguments[i]) : {};
var ownKeys = Object.keys(source); var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === 'function') { if (typeof Object.getOwnPropertySymbols === 'function') {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) { ownKeys.push.apply(ownKeys, Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable; return Object.getOwnPropertyDescriptor(source, sym).enumerable;
})); }));
} }

View File

@ -21,7 +21,11 @@ function collect(value, previousValue): Array<string> {
const values = value.split(","); const values = value.split(",");
return previousValue ? previousValue.concat(values) : values; if (previousValue) {
previousValue.push(...values);
return previousValue;
}
return values;
} }
program.option("-e, --eval [script]", "Evaluate script"); program.option("-e, --eval [script]", "Evaluate script");
@ -197,7 +201,7 @@ if (program.eval || program.print) {
} }
// add back on node and concat the sliced args // add back on node and concat the sliced args
process.argv = ["node"].concat(args); process.argv = ["node", ...args];
process.execArgv.push(fileURLToPath(import.meta.url)); process.execArgv.push(fileURLToPath(import.meta.url));
Module.runMain(); Module.runMain();

View File

@ -8,7 +8,7 @@ import path from "path";
import child_process from "child_process"; import child_process from "child_process";
import { fileURLToPath } from "url"; import { fileURLToPath } from "url";
let args = [ const args = [
path.join(path.dirname(fileURLToPath(import.meta.url)), "_babel-node"), path.join(path.dirname(fileURLToPath(import.meta.url)), "_babel-node"),
]; ];
@ -69,7 +69,7 @@ getV8Flags(async function (err, v8Flags) {
// append arguments passed after -- // append arguments passed after --
if (argSeparator > -1) { if (argSeparator > -1) {
args = args.concat(userArgs); args.push(...userArgs);
} }
try { try {

View File

@ -1961,7 +1961,8 @@ export default (superClass: Class<Parser>): Class<Parser> =>
if (failed && valid.length === 1) { if (failed && valid.length === 1) {
this.state = state; this.state = state;
this.state.noArrowAt = noArrowAt.concat(valid[0].start); noArrowAt.push(valid[0].start);
this.state.noArrowAt = noArrowAt;
({ consequent, failed } = this.tryParseConditionalConsequent()); ({ consequent, failed } = this.tryParseConditionalConsequent());
} }
} }

View File

@ -47,7 +47,7 @@ export default declare(api => {
} }
// push the rest of the original loop body onto our new body // push the rest of the original loop body onto our new body
block.body = block.body.concat(node.body.body); block.body.push(...node.body.body);
t.inherits(loop, node); t.inherits(loop, node);
t.inherits(loop.body, node.body); t.inherits(loop.body, node.body);

View File

@ -157,7 +157,7 @@ function applyTargetDecorators(path, state, decoratedProps) {
WARNING_CALLS.add(node.value); WARNING_CALLS.add(node.value);
acc = acc.concat([ acc.push(
t.assignmentExpression( t.assignmentExpression(
"=", "=",
t.cloneNode(descriptor), t.cloneNode(descriptor),
@ -184,9 +184,9 @@ function applyTargetDecorators(path, state, decoratedProps) {
]), ]),
]), ]),
), ),
]); );
} else { } else {
acc = acc.concat( acc.push(
t.callExpression(state.addHelper("applyDecoratedDescriptor"), [ t.callExpression(state.addHelper("applyDecoratedDescriptor"), [
t.cloneNode(target), t.cloneNode(target),
t.cloneNode(property), t.cloneNode(property),

View File

@ -136,9 +136,8 @@ export default function transformClass(
if (classState.userConstructor) { if (classState.userConstructor) {
const { constructorBody, userConstructor, construct } = classState; const { constructorBody, userConstructor, construct } = classState;
constructorBody.body = constructorBody.body.concat(
userConstructor.body.body, constructorBody.body.push(...userConstructor.body.body);
);
t.inherits(construct, userConstructor); t.inherits(construct, userConstructor);
t.inherits(constructorBody, userConstructor.body); t.inherits(constructorBody, userConstructor.body);
} }
@ -695,7 +694,7 @@ export default function transformClass(
extractDynamicKeys(); extractDynamicKeys();
let { body } = classState; const { body } = classState;
const { closureParams, closureArgs } = setupClosureParamsArgs(); const { closureParams, closureArgs } = setupClosureParamsArgs();
buildBody(); buildBody();
@ -712,8 +711,10 @@ export default function transformClass(
); );
} }
body = body.concat( body.push(
classState.staticPropBody.map(fn => fn(t.cloneNode(classState.classRef))), ...classState.staticPropBody.map(fn =>
fn(t.cloneNode(classState.classRef)),
),
); );
const isStrict = path.isInStrictMode(); const isStrict = path.isInStrictMode();

View File

@ -24,7 +24,7 @@ export default function transformWithoutHelper(loose, path, state) {
} }
// push the rest of the original loop body onto our new body // push the rest of the original loop body onto our new body
block.body = block.body.concat(node.body.body); block.body.push(...node.body.body);
t.inherits(loop, node); t.inherits(loop, node);
t.inherits(loop.body, node.body); t.inherits(loop.body, node.body);

View File

@ -295,7 +295,7 @@ export default declare((api, options) => {
const exportMap = Object.create(null); const exportMap = Object.create(null);
const modules = []; const modules = [];
let beforeBody = []; const beforeBody = [];
const setters = []; const setters = [];
const sources = []; const sources = [];
const variableIds = []; const variableIds = [];
@ -475,7 +475,7 @@ export default declare((api, options) => {
} }
modules.forEach(function (specifiers) { modules.forEach(function (specifiers) {
let setterBody = []; const setterBody = [];
const target = scope.generateUid(specifiers.key); const target = scope.generateUid(specifiers.key);
for (let specifier of specifiers.imports) { for (let specifier of specifiers.imports) {
@ -540,8 +540,8 @@ export default declare((api, options) => {
} }
} }
setterBody = setterBody.concat( setterBody.push(
constructExportCall( ...constructExportCall(
path, path,
t.identifier(exportIdent), t.identifier(exportIdent),
exportNames, exportNames,
@ -589,8 +589,8 @@ export default declare((api, options) => {
} }
if (exportNames.length) { if (exportNames.length) {
beforeBody = beforeBody.concat( beforeBody.push(
constructExportCall( ...constructExportCall(
path, path,
t.identifier(exportIdent), t.identifier(exportIdent),
exportNames, exportNames,

View File

@ -305,9 +305,7 @@ export default function convertFunctionRest(path) {
return true; return true;
} }
state.references = state.references.concat( state.references.push(...state.candidates.map(({ path }) => path));
state.candidates.map(({ path }) => path),
);
const start = t.numericLiteral(paramsCount); const start = t.numericLiteral(paramsCount);
const key = scope.generateUidIdentifier("key"); const key = scope.generateUidIdentifier("key");

View File

@ -46,7 +46,9 @@ function addCompletionRecords(
records: Completion[], records: Completion[],
context: CompletionContext, context: CompletionContext,
): Completion[] { ): Completion[] {
if (path) return records.concat(_getCompletionRecords(path, context)); if (path) {
records.push(..._getCompletionRecords(path, context));
}
return records; return records;
} }
@ -73,9 +75,9 @@ function completionRecordForSwitch(
if (normalCompletions.length) { if (normalCompletions.length) {
lastNormalCompletions = normalCompletions; lastNormalCompletions = normalCompletions;
} }
records = records.concat(breakCompletions); records.push(...breakCompletions);
} }
records = records.concat(lastNormalCompletions); records.push(...lastNormalCompletions);
return records; return records;
} }
@ -117,7 +119,7 @@ function getStatementListCompletion(
paths: NodePath[], paths: NodePath[],
context: CompletionContext, context: CompletionContext,
): Completion[] { ): Completion[] {
let completions = []; const completions = [];
if (context.canHaveBreak) { if (context.canHaveBreak) {
let lastNormalCompletions = []; let lastNormalCompletions = [];
for (let i = 0; i < paths.length; i++) { for (let i = 0; i < paths.length; i++) {
@ -155,11 +157,11 @@ function getStatementListCompletion(
// When we have seen normal completions from the last statement // When we have seen normal completions from the last statement
// it is safe to stop populating break and mark normal completions as break // it is safe to stop populating break and mark normal completions as break
normalCompletionToBreak(lastNormalCompletions); normalCompletionToBreak(lastNormalCompletions);
completions = completions.concat(lastNormalCompletions); completions.push(...lastNormalCompletions);
// Declarations have empty completion record, however they can not be nested // Declarations have empty completion record, however they can not be nested
// directly in return statement, i.e. `return (var a = 1)` is invalid. // directly in return statement, i.e. `return (var a = 1)` is invalid.
if (lastNormalCompletions.some(c => c.path.isDeclaration())) { if (lastNormalCompletions.some(c => c.path.isDeclaration())) {
completions = completions.concat(statementCompletions); completions.push(...statementCompletions);
replaceBreakStatementInBreakCompletion( replaceBreakStatementInBreakCompletion(
statementCompletions, statementCompletions,
/* reachable */ true, /* reachable */ true,
@ -170,7 +172,7 @@ function getStatementListCompletion(
/* reachable */ false, /* reachable */ false,
); );
} else { } else {
completions = completions.concat(statementCompletions); completions.push(...statementCompletions);
if (!context.shouldPopulateBreak) { if (!context.shouldPopulateBreak) {
replaceBreakStatementInBreakCompletion( replaceBreakStatementInBreakCompletion(
statementCompletions, statementCompletions,
@ -181,14 +183,18 @@ function getStatementListCompletion(
break; break;
} }
if (i === paths.length - 1) { if (i === paths.length - 1) {
completions = completions.concat(statementCompletions); completions.push(...statementCompletions);
} else { } else {
completions = completions.concat( lastNormalCompletions = [];
statementCompletions.filter(c => c.type === BREAK_COMPLETION), for (let i = 0; i < statementCompletions.length; i++) {
); const c = statementCompletions[i];
lastNormalCompletions = statementCompletions.filter( if (c.type === BREAK_COMPLETION) {
c => c.type === NORMAL_COMPLETION, completions.push(c);
); }
if (c.type === NORMAL_COMPLETION) {
lastNormalCompletions.push(c);
}
}
} }
} }
} else if (paths.length) { } else if (paths.length) {
@ -202,7 +208,7 @@ function getStatementListCompletion(
(pathCompletions.length === 1 && (pathCompletions.length === 1 &&
!pathCompletions[0].path.isVariableDeclaration()) !pathCompletions[0].path.isVariableDeclaration())
) { ) {
completions = completions.concat(pathCompletions); completions.push(...pathCompletions);
break; break;
} }
} }
@ -225,29 +231,25 @@ function _getCompletionRecords(
path.isLabeledStatement() path.isLabeledStatement()
) { ) {
// @ts-expect-error(flow->ts): todo // @ts-expect-error(flow->ts): todo
records = addCompletionRecords(path.get("body"), records, context); return addCompletionRecords(path.get("body"), records, context);
} else if (path.isProgram() || path.isBlockStatement()) { } else if (path.isProgram() || path.isBlockStatement()) {
records = records.concat( // @ts-expect-error(flow->ts): todo
// @ts-expect-error(flow->ts): todo return getStatementListCompletion(path.get("body"), context);
getStatementListCompletion(path.get("body"), context),
);
} else if (path.isFunction()) { } else if (path.isFunction()) {
return _getCompletionRecords(path.get("body"), context); return _getCompletionRecords(path.get("body"), context);
} else if (path.isTryStatement()) { } else if (path.isTryStatement()) {
records = addCompletionRecords(path.get("block"), records, context); records = addCompletionRecords(path.get("block"), records, context);
records = addCompletionRecords(path.get("handler"), records, context); records = addCompletionRecords(path.get("handler"), records, context);
} else if (path.isCatchClause()) { } else if (path.isCatchClause()) {
records = addCompletionRecords(path.get("body"), records, context); return addCompletionRecords(path.get("body"), records, context);
} else if (path.isSwitchStatement()) { } else if (path.isSwitchStatement()) {
records = completionRecordForSwitch(path.get("cases"), records, context); return completionRecordForSwitch(path.get("cases"), records, context);
} else if (path.isSwitchCase()) { } else if (path.isSwitchCase()) {
records = records.concat( return getStatementListCompletion(path.get("consequent"), {
getStatementListCompletion(path.get("consequent"), { canHaveBreak: true,
canHaveBreak: true, shouldPopulateBreak: false,
shouldPopulateBreak: false, inCaseClause: true,
inCaseClause: true, });
}),
);
} else if (path.isBreakStatement()) { } else if (path.isBreakStatement()) {
records.push(BreakCompletion(path)); records.push(BreakCompletion(path));
} else { } else {
@ -495,7 +497,7 @@ export function getBindingIdentifierPaths(
[x: string]: NodePath; [x: string]: NodePath;
} { } {
const path = this; const path = this;
let search = [].concat(path); const search = [path];
const ids = Object.create(null); const ids = Object.create(null);
while (search.length) { while (search.length) {
@ -517,7 +519,7 @@ export function getBindingIdentifierPaths(
if (id.isExportDeclaration()) { if (id.isExportDeclaration()) {
const declaration = id.get("declaration"); const declaration = id.get("declaration");
if (declaration.isDeclaration()) { if (t.isDeclaration(declaration)) {
search.push(declaration); search.push(declaration);
} }
continue; continue;
@ -537,8 +539,10 @@ export function getBindingIdentifierPaths(
for (let i = 0; i < keys.length; i++) { for (let i = 0; i < keys.length; i++) {
const key = keys[i]; const key = keys[i];
const child = id.get(key); const child = id.get(key);
if (Array.isArray(child) || child.node) { if (Array.isArray(child)) {
search = search.concat(child); search.push(...child);
} else if (child.node) {
search.push(child);
} }
} }
} }

View File

@ -84,7 +84,7 @@ function getTypeAnnotationBindingConstantViolations(binding, path, name) {
}*/ }*/
// add back on function constant violations since we can't track calls // add back on function constant violations since we can't track calls
constantViolations = constantViolations.concat(functionConstantViolations); constantViolations.push(...functionConstantViolations);
// push on inferred types of violated paths // push on inferred types of violated paths
for (const violation of constantViolations) { for (const violation of constantViolations) {

View File

@ -16,7 +16,7 @@ export default function addComments<T extends t.Node>(
if (type === "leading") { if (type === "leading") {
node[key] = comments.concat(node[key]); node[key] = comments.concat(node[key]);
} else { } else {
node[key] = node[key].concat(comments); node[key].push(...comments);
} }
} else { } else {
node[key] = comments; node[key] = comments;

View File

@ -17,13 +17,14 @@ function getQualifiedName(node: t.GenericTypeAnnotation["id"]) {
* Dedupe type annotations. * Dedupe type annotations.
*/ */
export default function removeTypeDuplicates( export default function removeTypeDuplicates(
// todo(babel-8): change type to Array<...>
nodes: ReadonlyArray<t.FlowType | false | null | undefined>, nodes: ReadonlyArray<t.FlowType | false | null | undefined>,
): t.FlowType[] { ): t.FlowType[] {
const generics = {}; const generics = {};
const bases = {}; const bases = {};
// store union type groups to circular references // store union type groups to circular references
const typeGroups = []; const typeGroups = new Set<t.FlowType[]>();
const types = []; const types = [];
@ -47,9 +48,10 @@ export default function removeTypeDuplicates(
} }
if (isUnionTypeAnnotation(node)) { if (isUnionTypeAnnotation(node)) {
if (typeGroups.indexOf(node.types) < 0) { if (!typeGroups.has(node.types)) {
// todo(babel-8): use .push when nodes is mutable
nodes = nodes.concat(node.types); nodes = nodes.concat(node.types);
typeGroups.push(node.types); typeGroups.add(node.types);
} }
continue; continue;
} }

View File

@ -15,7 +15,7 @@ export default function removeTypeDuplicates(
const bases = {}; const bases = {};
// store union type groups to circular references // store union type groups to circular references
const typeGroups = []; const typeGroups = new Set<t.TSType[]>();
const types = []; const types = [];
@ -40,9 +40,9 @@ export default function removeTypeDuplicates(
} }
if (isTSUnionType(node)) { if (isTSUnionType(node)) {
if (typeGroups.indexOf(node.types) < 0) { if (!typeGroups.has(node.types)) {
nodes = nodes.concat(node.types); nodes.push(...node.types);
typeGroups.push(node.types); typeGroups.add(node.types);
} }
continue; continue;
} }