Skip to content

Commit

Permalink
perf: replace String and Array indexOf method calls with includes met…
Browse files Browse the repository at this point in the history
…hod call (microsoft#55482)
  • Loading branch information
Havunen authored Aug 25, 2023
1 parent c3c5abb commit ec2bd4e
Show file tree
Hide file tree
Showing 46 changed files with 98 additions and 124 deletions.
2 changes: 1 addition & 1 deletion scripts/errorCheck.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ async function checkSourceFiles() {
let count = 0;
console.log("== List of errors not used in source ==");
for (const errName of errorNames) {
if (allSrc.indexOf(errName) < 0) {
if (!allSrc.includes(errName)) {
console.log(errName);
count++;
}
Expand Down
2 changes: 1 addition & 1 deletion scripts/eslint/rules/argument-trivia.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ module.exports = createRule({
}
}

const hasNewLine = sourceCodeText.slice(commentRangeEnd, argRangeStart).indexOf("\n") >= 0;
const hasNewLine = sourceCodeText.slice(commentRangeEnd, argRangeStart).includes("\n");
if (argRangeStart !== commentRangeEnd + 1 && !hasNewLine) {
// TODO(jakebailey): range should be whitespace
context.report({
Expand Down
2 changes: 1 addition & 1 deletion scripts/update-experimental-branches.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ async function main() {
const mergeTree = runSequence([
["git", ["merge-tree", mergeBase.trim(), branch, "experimental"]],
]);
if (mergeTree.indexOf(`===${"="}===`) >= 0) { // 7 equals is the center of the merge conflict marker
if (mergeTree.includes(`===${"="}===`)) { // 7 equals is the center of the merge conflict marker
throw new Error(`Merge conflict detected involving PR ${branch} with other experiment`);
}
// Merge (always producing a merge commit)
Expand Down
2 changes: 1 addition & 1 deletion src/cancellationToken/cancellationToken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ function createCancellationToken(args: string[]): ServerCancellationToken {
// in this case pipe name will be build dynamically as <cancellationPipeName><request_seq>.
if (cancellationPipeName.charAt(cancellationPipeName.length - 1) === "*") {
const namePrefix = cancellationPipeName.slice(0, -1);
if (namePrefix.length === 0 || namePrefix.indexOf("*") >= 0) {
if (namePrefix.length === 0 || namePrefix.includes("*")) {
throw new Error("Invalid name for template cancellation pipe: it should have length greater than 2 characters and contain only one '*'.");
}
let perRequestPipeName: string | undefined;
Expand Down
13 changes: 6 additions & 7 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -964,7 +964,6 @@ import {
SpreadElement,
startsWith,
Statement,
stringContains,
StringLiteral,
StringLiteralLike,
StringLiteralType,
Expand Down Expand Up @@ -7908,14 +7907,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
if (!specifier) {
specifier = getSpecifierForModuleSymbol(chain[0], context);
}
if (!(context.flags & NodeBuilderFlags.AllowNodeModulesRelativePaths) && getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.Classic && specifier.indexOf("/node_modules/") >= 0) {
if (!(context.flags & NodeBuilderFlags.AllowNodeModulesRelativePaths) && getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.Classic && specifier.includes("/node_modules/")) {
const oldSpecifier = specifier;
if (getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.Node16 || getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.NodeNext) {
// We might be able to write a portable import type using a mode override; try specifier generation again, but with a different mode set
const swappedMode = contextFile?.impliedNodeFormat === ModuleKind.ESNext ? ModuleKind.CommonJS : ModuleKind.ESNext;
specifier = getSpecifierForModuleSymbol(chain[0], context, swappedMode);

if (specifier.indexOf("/node_modules/") >= 0) {
if (specifier.includes("/node_modules/")) {
// Still unreachable :(
specifier = oldSpecifier;
}
Expand Down Expand Up @@ -8661,7 +8660,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
if (group.length > 1) {
// remove group members from statements and then merge group members and add back to statements
statements = [
...filter(statements, s => group.indexOf(s as ExportDeclaration) === -1),
...filter(statements, s => !group.includes(s as ExportDeclaration)),
factory.createExportDeclaration(
/*modifiers*/ undefined,
/*isTypeOnly*/ false,
Expand Down Expand Up @@ -24250,7 +24249,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
const originalKeywordKind = identifierToKeywordKind(param.name);
if (
(isCallSignatureDeclaration(param.parent) || isMethodSignature(param.parent) || isFunctionTypeNode(param.parent)) &&
param.parent.parameters.indexOf(param) > -1 &&
param.parent.parameters.includes(param) &&
(resolveName(param, param.name.escapedText, SymbolFlags.Type, /*nameNotFoundMessage*/ undefined, param.name.escapedText, /*isUse*/ true) ||
originalKeywordKind && isTypeNodeKind(originalKeywordKind))
) {
Expand Down Expand Up @@ -30962,7 +30961,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}

function isHyphenatedJsxName(name: string | __String) {
return stringContains(name as string, "-");
return (name as string).includes("-");
}

/**
Expand Down Expand Up @@ -49648,7 +49647,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
// Realism (size) checking
// We should test against `getTextOfNode(node)` rather than `node.text`, because `node.text` for large numeric literals can contain "."
// e.g. `node.text` for numeric literal `1100000000000000000000` is `1.1e21`.
const isFractional = getTextOfNode(node).indexOf(".") !== -1;
const isFractional = getTextOfNode(node).includes(".");
const isScientific = node.numericLiteralFlags & TokenFlags.Scientific;

// Scientific notation (e.g. 2e54 and 1e00000000010) can't be converted to bigint
Expand Down
5 changes: 2 additions & 3 deletions src/compiler/commandLineParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,6 @@ import {
returnTrue,
ScriptTarget,
startsWith,
stringContains,
StringLiteral,
SyntaxKind,
sys,
Expand Down Expand Up @@ -1710,7 +1709,7 @@ export function parseListTypeOption(opt: CommandLineOptionOfListType, value = ""
if (startsWith(value, "-")) {
return undefined;
}
if (opt.type === "listOrElement" && !stringContains(value, ",")) {
if (opt.type === "listOrElement" && !value.includes(",")) {
return validateJsonOptionValue(opt, value, errors);
}
if (value === "") {
Expand Down Expand Up @@ -3078,7 +3077,7 @@ function parseConfig(
basePath = normalizeSlashes(basePath);
const resolvedPath = getNormalizedAbsolutePath(configFileName || "", basePath);

if (resolutionStack.indexOf(resolvedPath) >= 0) {
if (resolutionStack.includes(resolvedPath)) {
errors.push(createCompilerDiagnostic(Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, [...resolutionStack, resolvedPath].join(" -> ")));
return { raw: json || convertToObject(sourceFile!, errors) };
}
Expand Down
5 changes: 0 additions & 5 deletions src/compiler/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2484,11 +2484,6 @@ export function tryRemoveSuffix(str: string, suffix: string): string | undefined
return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined;
}

/** @internal */
export function stringContains(str: string, substring: string): boolean {
return str.indexOf(substring) !== -1;
}

/**
* Takes a string like "jquery-min.4.2.3" and returns "jquery"
*
Expand Down
7 changes: 3 additions & 4 deletions src/compiler/emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,6 @@ import {
SpreadElement,
stableSort,
Statement,
stringContains,
StringLiteral,
supportedJSExtensionsFlat,
SwitchStatement,
Expand Down Expand Up @@ -3065,9 +3064,9 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri
// If the number will be printed verbatim and it doesn't already contain a dot or an exponent indicator, add one
// if the expression doesn't have any comments that will be emitted.
return !(expression.numericLiteralFlags & TokenFlags.WithSpecifier)
&& !stringContains(text, tokenToString(SyntaxKind.DotToken)!)
&& !stringContains(text, String.fromCharCode(CharacterCodes.E))
&& !stringContains(text, String.fromCharCode(CharacterCodes.e));
&& !text.includes(tokenToString(SyntaxKind.DotToken)!)
&& !text.includes(String.fromCharCode(CharacterCodes.E))
&& !text.includes(String.fromCharCode(CharacterCodes.e));
}
else if (isAccessExpression(expression)) {
// check if constant enum value is a non-negative integer
Expand Down
29 changes: 14 additions & 15 deletions src/compiler/moduleNameResolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,6 @@ import {
sort,
SourceFile,
startsWith,
stringContains,
supportedDeclarationExtensions,
supportedJSExtensionsFlat,
supportedTSImplementationExtensions,
Expand Down Expand Up @@ -1808,7 +1807,7 @@ function nodeModuleNameResolverWorker(features: NodeResolutionFeatures, moduleNa
&& features & NodeResolutionFeatures.Exports
&& !isExternalModuleNameRelative(moduleName)
&& !extensionIsOk(Extensions.TypeScript | Extensions.Declaration, result.value.resolved.extension)
&& conditions.indexOf("import") > -1
&& conditions.includes("import")
) {
traceIfEnabled(state, Diagnostics.Resolution_of_non_relative_name_failed_trying_with_modern_Node_resolution_features_disabled_to_see_if_npm_library_needs_configuration_update);
const diagnosticState = {
Expand Down Expand Up @@ -1849,7 +1848,7 @@ function nodeModuleNameResolverWorker(features: NodeResolutionFeatures, moduleNa
resolved = loadModuleFromSelfNameReference(extensions, moduleName, containingDirectory, state, cache, redirectedReference);
}
if (!resolved) {
if (moduleName.indexOf(":") > -1) {
if (moduleName.includes(":")) {
if (traceEnabled) {
trace(host, Diagnostics.Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1, moduleName, formatExtensions(extensions));
}
Expand Down Expand Up @@ -1944,7 +1943,7 @@ function nodeLoadModuleByRelativeName(extensions: Extensions, candidate: string,
export const nodeModulesPathPart = "/node_modules/";
/** @internal */
export function pathContainsNodeModules(path: string): boolean {
return stringContains(path, nodeModulesPathPart);
return path.includes(nodeModulesPathPart);
}

/**
Expand Down Expand Up @@ -2006,7 +2005,7 @@ function loadModuleFromFile(extensions: Extensions, candidate: string, onlyRecor

function loadModuleFromFileNoImplicitExtensions(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState): PathAndExtension | undefined {
const filename = getBaseFileName(candidate);
if (filename.indexOf(".") === -1) {
if (!filename.includes(".")) {
return undefined; // extensionless import, no lookups performed, since we don't support extensionless files
}
let extensionless = removeFileExtension(candidate);
Expand Down Expand Up @@ -2223,7 +2222,7 @@ function loadEntrypointsFromExportMap(

function loadEntrypointsFromTargetExports(target: unknown): boolean | undefined {
if (typeof target === "string" && startsWith(target, "./")) {
if (target.indexOf("*") >= 0 && state.host.readDirectory) {
if (target.includes("*") && state.host.readDirectory) {
if (target.indexOf("*") !== target.lastIndexOf("*")) {
return false;
}
Expand All @@ -2243,7 +2242,7 @@ function loadEntrypointsFromExportMap(
}
else {
const partsAfterFirst = getPathComponents(target).slice(2);
if (partsAfterFirst.indexOf("..") >= 0 || partsAfterFirst.indexOf(".") >= 0 || partsAfterFirst.indexOf("node_modules") >= 0) {
if (partsAfterFirst.includes("..") || partsAfterFirst.includes(".") || partsAfterFirst.includes("node_modules")) {
return false;
}
const resolvedTarget = combinePaths(scope.packageDirectory, target);
Expand Down Expand Up @@ -2609,11 +2608,11 @@ export function comparePatternKeys(a: string, b: string) {
function loadModuleFromImportsOrExports(extensions: Extensions, state: ModuleResolutionState, cache: ModuleResolutionCache | undefined, redirectedReference: ResolvedProjectReference | undefined, moduleName: string, lookupTable: object, scope: PackageJsonInfo, isImports: boolean): SearchResult<Resolved> | undefined {
const loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports);

if (!endsWith(moduleName, directorySeparator) && moduleName.indexOf("*") === -1 && hasProperty(lookupTable, moduleName)) {
if (!endsWith(moduleName, directorySeparator) && !moduleName.includes("*") && hasProperty(lookupTable, moduleName)) {
const target = (lookupTable as { [idx: string]: unknown; })[moduleName];
return loadModuleFromTargetImportOrExport(target, /*subpath*/ "", /*pattern*/ false, moduleName);
}
const expandingKeys = sort(filter(getOwnKeys(lookupTable as MapLike<unknown>), k => k.indexOf("*") !== -1 || endsWith(k, "/")), comparePatternKeys);
const expandingKeys = sort(filter(getOwnKeys(lookupTable as MapLike<unknown>), k => k.includes("*") || endsWith(k, "/")), comparePatternKeys);
for (const potentialTarget of expandingKeys) {
if (state.features & NodeResolutionFeatures.ExportsPatternTrailers && matchesPatternWithTrailer(potentialTarget, moduleName)) {
const target = (lookupTable as { [idx: string]: unknown; })[potentialTarget];
Expand Down Expand Up @@ -2677,7 +2676,7 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo
}
const parts = pathIsRelative(target) ? getPathComponents(target).slice(1) : getPathComponents(target);
const partsAfterFirst = parts.slice(1);
if (partsAfterFirst.indexOf("..") >= 0 || partsAfterFirst.indexOf(".") >= 0 || partsAfterFirst.indexOf("node_modules") >= 0) {
if (partsAfterFirst.includes("..") || partsAfterFirst.includes(".") || partsAfterFirst.includes("node_modules")) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
}
Expand All @@ -2687,7 +2686,7 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo
// TODO: Assert that `resolvedTarget` is actually within the package directory? That's what the spec says.... but I'm not sure we need
// to be in the business of validating everyone's import and export map correctness.
const subpathParts = getPathComponents(subpath);
if (subpathParts.indexOf("..") >= 0 || subpathParts.indexOf(".") >= 0 || subpathParts.indexOf("node_modules") >= 0) {
if (subpathParts.includes("..") || subpathParts.includes(".") || subpathParts.includes("node_modules")) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName);
}
Expand All @@ -2706,7 +2705,7 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo
if (!Array.isArray(target)) {
traceIfEnabled(state, Diagnostics.Entering_conditional_exports);
for (const condition of getOwnKeys(target as MapLike<unknown>)) {
if (condition === "default" || state.conditions.indexOf(condition) >= 0 || isApplicableVersionedTypesKey(state.conditions, condition)) {
if (condition === "default" || state.conditions.includes(condition) || isApplicableVersionedTypesKey(state.conditions, condition)) {
traceIfEnabled(state, Diagnostics.Matched_0_condition_1, isImports ? "imports" : "exports", condition);
const subTarget = (target as MapLike<unknown>)[condition];
const result = loadModuleFromTargetImportOrExport(subTarget, subpath, pattern, key);
Expand Down Expand Up @@ -2772,7 +2771,7 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo
if (
!state.isConfigLookup
&& (state.compilerOptions.declarationDir || state.compilerOptions.outDir)
&& finalPath.indexOf("/node_modules/") === -1
&& !finalPath.includes("/node_modules/")
&& (state.compilerOptions.configFile ? containsPath(scope.packageDirectory, toAbsolutePath(state.compilerOptions.configFile.fileName), !useCaseSensitiveFileNames(state)) : true)
) {
// So that all means we'll only try these guesses for files outside `node_modules` in a directory where the `package.json` and `tsconfig.json` are siblings.
Expand Down Expand Up @@ -2876,7 +2875,7 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo

/** @internal */
export function isApplicableVersionedTypesKey(conditions: readonly string[], key: string) {
if (conditions.indexOf("types") === -1) return false; // only apply versioned types conditions if the types condition is applied
if (!conditions.includes("types")) return false; // only apply versioned types conditions if the types condition is applied
if (!startsWith(key, "types@")) return false;
const range = VersionRange.tryParse(key.substring("types@".length));
if (!range) return false;
Expand Down Expand Up @@ -3099,7 +3098,7 @@ export function getPackageNameFromTypesPackageName(mangledName: string): string

/** @internal */
export function unmangleScopedPackageName(typesPackageName: string): string {
return stringContains(typesPackageName, mangledScopedPackageSeparator) ?
return typesPackageName.includes(mangledScopedPackageSeparator) ?
"@" + typesPackageName.replace(mangledScopedPackageSeparator, directorySeparator) :
typesPackageName;
}
Expand Down
Loading

0 comments on commit ec2bd4e

Please sign in to comment.