Unverified Commit abe8b1e0 authored by Quentin's avatar Quentin Committed by GitHub

Improve performance of String.prototype.split uses (#56746)

This PR adds the optional `limit` parameter on String.prototype.split uses.

> If provided, splits the string at each occurrence of the specified separator, but stops when limit entries have been placed in the array. Any leftover text is not included in the array at all.

[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split#syntax)

While the performance gain may not be significant for small texts, it can be huge for large ones.

I made a benchmark on the following repository : https://github.com/Yovach/benchmark-nodejs

On my machine, I get the following results:
`node index.js`
> normal 1: 570.092ms
> normal 50: 2.284s
> normal 100: 3.543s

`node index-optimized.js`
> optmized 1: 644.301ms
> optmized 50: 929.39ms
> optmized 100: 1.020s

The "benchmarks" numbers are : 
- "lorem-1" file contains 1 paragraph of "lorem ipsum"
- "lorem-50" file contains 50 paragraphes of "lorem ipsum"
- "lorem-100" file contains 100 paragraphes of "lorem ipsum"
parent 8e203457
......@@ -189,7 +189,7 @@ async function prepareDocumentMapEntry(
// Checks if the links point to existing documents
function validateInternalLink(errors: Errors, href: string): void {
// /docs/api/example#heading -> ["api/example", "heading""]
const [link, hash] = href.replace(DOCS_PATH, '').split('#')
const [link, hash] = href.replace(DOCS_PATH, '').split('#', 2)
let foundPage
......
......@@ -33,7 +33,7 @@ export = defineRule({
hrefValue.startsWith('https://fonts.googleapis.com/css')
if (isGoogleFont) {
const params = new URLSearchParams(hrefValue.split('?')[1])
const params = new URLSearchParams(hrefValue.split('?', 2)[1])
const displayValue = params.get('display')
if (!params.has('display')) {
......
......@@ -66,7 +66,7 @@ export = defineRule({
return
}
const document = context.getFilename().split('pages')[1]
const document = context.getFilename().split('pages', 2)[1]
if (document && path.parse(document).name.startsWith('_document')) {
return
}
......
......@@ -20,7 +20,7 @@ export = defineRule({
return
}
const document = context.getFilename().split('pages')[1]
const document = context.getFilename().split('pages', 2)[1]
if (!document) {
return
}
......
......@@ -16,7 +16,7 @@ export = defineRule({
create(context) {
return {
JSXOpeningElement(node) {
const document = context.getFilename().split('pages')[1]
const document = context.getFilename().split('pages', 2)[1]
if (!document) {
return
}
......
......@@ -73,7 +73,7 @@ export = defineRule({
}
return {
ExportNamedDeclaration(node) {
const page = context.getFilename().split('pages')[1]
const page = context.getFilename().split('pages', 2)[1]
if (!page || path.parse(page).dir.startsWith('/api')) {
return
}
......
......@@ -43,8 +43,8 @@ export function normalizeURL(url: string) {
if (!url) {
return
}
url = url.split('?')[0]
url = url.split('#')[0]
url = url.split('?', 1)[0]
url = url.split('#', 1)[0]
url = url = url.replace(/(\/index\.html)$/, '/')
// Empty URLs should not be trailed with `/`, e.g. `#heading`
if (url === '') {
......
......@@ -95,7 +95,7 @@ const nextFontGoogleFontLoader: FontLoader = async ({
}
// CSS Variables may be set on a body tag, ignore them to keep the CSS module pure
fontFaceDeclarations = fontFaceDeclarations.split('body {')[0]
fontFaceDeclarations = fontFaceDeclarations.split('body {', 1)[0]
// Find font files to download, provide the array of subsets we want to preload if preloading is enabled
const fontFiles = findFontFilesInCss(
......
......@@ -7,8 +7,8 @@ export function sortFontsVariantValues(valA: string, valB: string) {
// If both values contain commas, it indicates they are in "ital,wght" format
if (valA.includes(',') && valB.includes(',')) {
// Split the values into prefix and suffix
const [aPrefix, aSuffix] = valA.split(',')
const [bPrefix, bSuffix] = valB.split(',')
const [aPrefix, aSuffix] = valA.split(',', 2)
const [bPrefix, bSuffix] = valB.split(',', 2)
// Compare the prefixes (ital values)
if (aPrefix === bPrefix) {
......
......@@ -329,8 +329,7 @@ const plugin = (options: any = {}) => {
return parsedDeclaration
}
const splittedUrl = url.split(/(\?)?#/)
const [pathname, query, hashOrQuery] = splittedUrl
const [pathname, query, hashOrQuery] = url.split(/(\?)?#/, 3)
let hash = query ? '?' : ''
hash += hashOrQuery ? `#${hashOrQuery}` : ''
......
......@@ -178,7 +178,7 @@ async function createTreeCodeFromPath(
rootLayout: string | undefined
globalError: string | undefined
}> {
const splittedPath = pagePath.split(/[\\/]/)
const splittedPath = pagePath.split(/[\\/]/, 1)
const isNotFoundRoute = page === '/_not-found'
const isDefaultNotFound = isAppBuiltinNotFoundPage(pagePath)
const appDirPrefix = isDefaultNotFound ? APP_DIR_ALIAS : splittedPath[0]
......
......@@ -16,7 +16,7 @@ type MetadataRouteLoaderOptions = {
export function getFilenameAndExtension(resourcePath: string) {
const filename = path.basename(resourcePath)
const [name, ext] = filename.split('.')
const [name, ext] = filename.split('.', 2)
return { name, ext }
}
......
......@@ -97,7 +97,7 @@ export default async function resolveUrlLoader(
(typeof exception === 'string' && exception) ||
(exception instanceof Error && [
exception.message,
(exception as any).stack.split('\n')[1].trim(),
(exception as any).stack.split('\n', 2)[1].trim(),
]) ||
[]
)
......
......@@ -13,7 +13,7 @@ export function linkGc() {
if (link.dataset.precedence?.startsWith('next')) {
const href = link.getAttribute('href')
if (href) {
const [resource, version] = href.split('?v=')
const [resource, version] = href.split('?v=', 2)
if (version) {
const currentOrigin = window.location.origin
const allLinks = [
......@@ -35,7 +35,7 @@ export function linkGc() {
if (otherLink.dataset.precedence?.startsWith('next')) {
const otherHref = otherLink.getAttribute('href')
if (otherHref) {
const [, otherVersion] = otherHref.split('?v=')
const [, otherVersion] = otherHref.split('?v=', 2)
if (!otherVersion || +otherVersion < +version) {
// Delay the removal of the stylesheet to avoid FOUC
// caused by `@font-face` rules, as they seem to be
......
......@@ -8,7 +8,7 @@ export type TerminalProps = { content: string }
function getFile(lines: string[]) {
const contentFileName = lines.shift()
if (!contentFileName) return null
const [fileName, line, column] = contentFileName.split(':')
const [fileName, line, column] = contentFileName.split(':', 3)
const parsedLine = Number(line)
const parsedColumn = Number(column)
......
......@@ -19,7 +19,7 @@ export function getSocketUrl(assetPrefix: string): string {
}`
if (normalizedAssetPrefix.startsWith('http')) {
url = `${protocol}://${normalizedAssetPrefix.split('://')[1]}`
url = `${protocol}://${normalizedAssetPrefix.split('://', 2)[1]}`
}
return url
......
......@@ -26,7 +26,7 @@ export function parseComponentStack(
/^(webpack-internal:\/\/\/|file:\/\/)(\(.*\)\/)?/,
''
)
const [file, lineNumber, column] = modulePath?.split(':') ?? []
const [file, lineNumber, column] = modulePath?.split(':', 3) ?? []
componentStackFrames.push({
component,
......
......@@ -104,5 +104,5 @@ export function getRedirectTypeFromError<U extends string>(
throw new Error('Not a redirect error')
}
return error.digest.split(';', 3)[1] as RedirectType
return error.digest.split(';', 2)[1] as RedirectType
}
......@@ -41,8 +41,8 @@ export function handleMutable(
false,
onlyHashChange:
!!mutable.hashFragment &&
state.canonicalUrl.split('#')[0] ===
mutable.canonicalUrl?.split('#')[0],
state.canonicalUrl.split('#', 1)[0] ===
mutable.canonicalUrl?.split('#', 1)[0],
hashFragment: shouldScroll
? // Empty hash should trigger default behavior of scrolling layout into view.
// #top is handled in layout-router.
......
......@@ -16,7 +16,7 @@ export default function initializeBuildWatcher(
position = 'bottom-right'
) {
const shadowHost = document.createElement('div')
const [verticalProperty, horizontalProperty] = position.split('-') as [
const [verticalProperty, horizontalProperty] = position.split('-', 2) as [
VerticalPosition,
HorizonalPosition
]
......
......@@ -71,7 +71,7 @@ export function connectHMR(options: { path: string; assetPrefix: string }) {
}`
if (assetPrefix.startsWith('http')) {
url = `${protocol}://${assetPrefix.split('://')[1]}`
url = `${protocol}://${assetPrefix.split('://', 2)[1]}`
}
source = new window.WebSocket(`${url}${options.path}`)
......
......@@ -163,7 +163,7 @@ function handleLoading(
function getDynamicProps(
fetchPriority?: string
): Record<string, string | undefined> {
const [majorStr, minorStr] = version.split('.')
const [majorStr, minorStr] = version.split('.', 2)
const major = parseInt(majorStr, 10)
const minor = parseInt(minorStr, 10)
if (major > 18 || (major === 18 && minor >= 3)) {
......
......@@ -39,7 +39,7 @@ export function resolveHref(
? urlAsString.slice(urlProtoMatch[0].length)
: urlAsString
const urlParts = urlAsStringNoProto.split('?')
const urlParts = urlAsStringNoProto.split('?', 1)
if ((urlParts[0] || '').match(/(\/\/|\\)/)) {
console.error(
......
......@@ -102,7 +102,7 @@ function getForwardedHeaders(
Array.isArray(rawSetCookies) ? rawSetCookies : [rawSetCookies]
).map((setCookie) => {
// remove the suffixes like 'HttpOnly' and 'SameSite'
const [cookie] = `${setCookie}`.split(';')
const [cookie] = `${setCookie}`.split(';', 1)
return cookie
})
......
......@@ -579,7 +579,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
if (this.i18nProvider) {
// Remove the port from the hostname if present.
const hostname = req?.headers.host?.split(':')[0].toLowerCase()
const hostname = req?.headers.host?.split(':', 1)[0].toLowerCase()
const domainLocale = this.i18nProvider.detectDomainLocale(hostname)
const defaultLocale =
......@@ -792,7 +792,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
return origSetHeader(name, val)
}
const urlParts = (req.url || '').split('?')
const urlParts = (req.url || '').split('?', 1)
const urlNoQuery = urlParts[0]
// this normalizes repeated slashes in the path e.g. hello//world ->
......
......@@ -55,7 +55,7 @@ export class I18NProvider {
const domain = domainLocale.domain.toLowerCase()
return {
defaultLocale: domainLocale.defaultLocale.toLowerCase(),
hostname: domain.split(':')[0],
hostname: domain.split(':', 1)[0],
domain,
locales: domainLocale.locales?.map((locale) => locale.toLowerCase()),
http: domainLocale.http,
......@@ -154,7 +154,7 @@ export class I18NProvider {
// The first segment will be empty, because it has a leading `/`. If
// there is no further segment, there is no locale (or it's the default).
const segments = pathname.split('/')
const segments = pathname.split('/', 2)
if (!segments[1])
return {
detectedLocale,
......
......@@ -294,7 +294,7 @@ export class ImageOptimizerCache {
const now = Date.now()
for (const file of files) {
const [maxAgeSt, expireAtSt, etag, extension] = file.split('.')
const [maxAgeSt, expireAtSt, etag, extension] = file.split('.', 4)
const buffer = await promises.readFile(join(cacheDir, file))
const expireAt = Number(expireAtSt)
const maxAge = Number(maxAgeSt)
......@@ -373,7 +373,7 @@ function parseCacheControl(str: string | null): Map<string, string> {
return map
}
for (let directive of str.split(',')) {
let [key, value] = directive.trim().split('=')
let [key, value] = directive.trim().split('=', 2)
key = key.toLowerCase()
if (value) {
value = value.toLowerCase()
......@@ -686,13 +686,13 @@ function getFileNameWithExtension(
url: string,
contentType: string | null
): string {
const [urlWithoutQueryParams] = url.split('?')
const [urlWithoutQueryParams] = url.split('?', 1)
const fileNameWithExtension = urlWithoutQueryParams.split('/').pop()
if (!contentType || !fileNameWithExtension) {
return 'image.bin'
}
const [fileName] = fileNameWithExtension.split('.')
const [fileName] = fileNameWithExtension.split('.', 1)
const extension = getExtension(contentType)
return `${fileName}.${extension}`
}
......
......@@ -116,7 +116,7 @@ export function getResolveRoutes(
let parsedUrl = url.parse(req.url || '', true) as NextUrlWithParsedQuery
let didRewrite = false
const urlParts = (req.url || '').split('?')
const urlParts = (req.url || '').split('?', 1)
const urlNoQuery = urlParts[0]
// this normalizes repeated slashes in the path e.g. hello//world ->
......
......@@ -18,7 +18,7 @@ export const getDebugPort = () => {
localArg.startsWith('--inspect') ||
localArg.startsWith('--inspect-brk')
)
?.split('=')[1] ??
?.split('=', 2)[1] ??
process.env.NODE_OPTIONS?.match?.(/--inspect(-brk)?(=(\S+))?( |$)/)?.[3]
return debugPortStr ? parseInt(debugPortStr, 10) : 9229
}
......
......@@ -1547,7 +1547,8 @@ export async function renderToHTMLImpl(
}
const [renderTargetPrefix, renderTargetSuffix] = documentHTML.split(
'<next-js-internal-body-render-target></next-js-internal-body-render-target>'
'<next-js-internal-body-render-target></next-js-internal-body-render-target>',
2
)
let prefix = ''
......
......@@ -426,7 +426,7 @@ export async function continueFizzStream(
const closeTag = '</body></html>'
// Suffix itself might contain close tags at the end, so we need to split it.
const suffixUnclosed = suffix ? suffix.split(closeTag)[0] : null
const suffixUnclosed = suffix ? suffix.split(closeTag, 1)[0] : null
if (generateStaticHTML) {
await renderStream.allReady
......
......@@ -14,7 +14,7 @@ export function getHostname(
// hostname.
let hostname: string
if (headers?.host && !Array.isArray(headers.host)) {
hostname = headers.host.toString().split(':')[0]
hostname = headers.host.toString().split(':', 1)[0]
} else if (parsed.hostname) {
hostname = parsed.hostname
} else return
......
......@@ -13,7 +13,7 @@ export function detectDomainLocale(
for (const item of domainItems) {
// remove port if present
const domainHostname = item.domain?.split(':')[0].toLowerCase()
const domainHostname = item.domain?.split(':', 1)[0].toLowerCase()
if (
hostname === domainHostname ||
detectedLocale === item.defaultLocale.toLowerCase() ||
......
......@@ -2219,8 +2219,8 @@ export default class Router implements BaseRouter {
onlyAHashChange(as: string): boolean {
if (!this.asPath) return false
const [oldUrlNoHash, oldHash] = this.asPath.split('#')
const [newUrlNoHash, newHash] = as.split('#')
const [oldUrlNoHash, oldHash] = this.asPath.split('#', 2)
const [newUrlNoHash, newHash] = as.split('#', 2)
// Makes sure we scroll to the provided hash if the url/hash are the same
if (newHash && oldUrlNoHash === newUrlNoHash && oldHash === newHash) {
......@@ -2240,7 +2240,7 @@ export default class Router implements BaseRouter {
}
scrollToHash(as: string): void {
const [, hash = ''] = as.split('#')
const [, hash = ''] = as.split('#', 2)
handleSmoothScroll(
() => {
......
......@@ -81,7 +81,7 @@ export function matchHas(
case 'host': {
const { host } = req?.headers || {}
// remove port from host if present
const hostname = host?.split(':')[0].toLowerCase()
const hostname = host?.split(':', 1)[0].toLowerCase()
value = hostname
break
}
......@@ -257,7 +257,7 @@ export function prepareDestination(args: {
try {
newUrl = destPathCompiler(args.params)
const [pathname, hash] = newUrl.split('#')
const [pathname, hash] = newUrl.split('#', 2)
parsedDestination.hostname = destHostnameCompiler(args.params)
parsedDestination.pathname = pathname
parsedDestination.hash = `${hash ? '#' : ''}${hash || ''}`
......
......@@ -118,7 +118,7 @@ describe('404-page-router', () => {
describe.each(urls)('for $url', ({ url, pathname, asPath }) => {
it('should have the correct router parameters after it is ready', async () => {
const query = url.split('?')[1] ?? ''
const query = url.split('?', 2)[1] ?? ''
const browser = await webdriver(next.url, url)
try {
......
......@@ -45,7 +45,7 @@ createNextDescribe(
await browser.elementByCss('#cookie').click()
await check(async () => {
const res = (await browser.elementByCss('h1').text()) || ''
const id = res.split(':')
const id = res.split(':', 2)
return id[0] === id[1] && id[0] ? 'same' : 'different'
}, 'same')
......@@ -59,7 +59,7 @@ createNextDescribe(
await browser.elementByCss('#setCookie').click()
await check(async () => {
const res = (await browser.elementByCss('h1').text()) || ''
const id = res.split(':')
const id = res.split(':', 3)
return id[0] === id[1] && id[0] === id[2] && id[0]
? 'same'
: 'different'
......
......@@ -62,7 +62,7 @@ createNextDescribe(
'/static/three/data.json',
])('responds correctly on %s', async (path) => {
expect(JSON.parse(await next.render(basePath + path))).toEqual({
params: { slug: path.split('/')[2] },
params: { slug: path.split('/', 3)[2] },
now: expect.any(Number),
})
if (isNextStart) {
......@@ -85,7 +85,7 @@ createNextDescribe(
])('revalidates correctly on %s', async (path) => {
const data = JSON.parse(await next.render(basePath + path))
expect(data).toEqual({
params: { slug: path.split('/')[2] },
params: { slug: path.split('/', 3)[2] },
now: expect.any(Number),
})
......
......@@ -11,13 +11,13 @@ function parseLogsFromCli(cliOutput: string) {
return logs.reduce((parsedLogs, log) => {
if (log.includes('Cache missed reason')) {
// cache miss reason
const reasonSegment = log.split('Cache missed reason: ')[1].trim()
const reasonSegment = log.split('Cache missed reason: ', 2)[1].trim()
const reason = reasonSegment.slice(1, -1)
parsedLogs[parsedLogs.length - 1].cache = reason
} else {
// request info
const trimmedLog = log.replace(/^[^a-zA-Z]+/, '')
const parts = trimmedLog.split(' ')
const parts = trimmedLog.split(' ', 5)
const method = parts[0]
const url = parts[1]
const statusCode = parseInt(parts[2])
......
......@@ -1906,7 +1906,7 @@ createNextDescribe(
it('should skip cache in draft mode', async () => {
const draftRes = await next.fetch('/api/draft-mode?status=enable')
const setCookie = draftRes.headers.get('set-cookie')
const cookieHeader = { Cookie: setCookie?.split(';')[0] }
const cookieHeader = { Cookie: setCookie?.split(';', 1)[0] }
expect(cookieHeader.Cookie).toBeTruthy()
......
......@@ -22,7 +22,7 @@ createNextDescribe(
// convert pretty-bytes format into bytes so we can compare units
const sizeToBytes = (size: string) => {
const units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
const [value, unit] = size.split(' ')
const [value, unit] = size.split(' ', 2)
const exp = units.indexOf(unit)
return parseFloat(value) * Math.pow(1024, exp)
}
......
......@@ -152,7 +152,7 @@ createNextDescribe(
.toArray()
.map((el) => {
return {
href: $(el).attr('href').split('?')[0],
href: $(el).attr('href').split('?', 1)[0],
sizes: $(el).attr('sizes'),
type: $(el).attr('type'),
}
......@@ -175,7 +175,7 @@ createNextDescribe(
.toArray()
.map((el) => {
return {
href: $(el).attr('href').split('?')[0],
href: $(el).attr('href').split('?', 1)[0],
sizes: $(el).attr('sizes'),
type: $(el).attr('type'),
}
......
......@@ -46,7 +46,7 @@ createNextDescribe(
clientReferenceManifest.clientModules
)
clientModulesNames.every((name) => {
const [, key] = name.split('#')
const [, key] = name.split('#', 2)
return key === undefined || key === '' || key === 'default'
})
......
......@@ -628,8 +628,8 @@ describe('Middleware Rewrite', () => {
// node-fetch bundles the cookies as string in the Response
const cookieArray = res.headers.raw()['set-cookie']
for (const cookie of cookieArray) {
let individualCookieParams = cookie.split(';')
let individualCookie = individualCookieParams[0].split('=')
let individualCookieParams = cookie.split(';', 1)
let individualCookie = individualCookieParams[0].split('=', 2)
if (individualCookie[0] === cookieName) {
return individualCookie[1]
}
......
......@@ -114,7 +114,7 @@ export class NextDevInstance extends NextInstance {
msg.includes('started server on') &&
msg.includes('url:')
) {
this._url = msg.split('url: ').pop().split(/\s/)[0].trim()
this._url = msg.split('url: ').pop().split(/\s/, 1)[0].trim()
resolveServer()
}
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment