Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: avoid parseRequest #15617

Merged
merged 5 commits into from
Jan 16, 2024
Merged

perf: avoid parseRequest #15617

merged 5 commits into from
Jan 16, 2024

Conversation

bluwy
Copy link
Member

@bluwy bluwy commented Jan 16, 2024

Description

ref #14420 (comment)

Avoid parseRequest function and use plain regex instead.

Perf link too long that it doesn't work :( Here's another benchmark: https://jsperf.app/nikobo

In case that ever fails again, here's the benchmark code:

Details
// Setup
// ufo
function parseQuery(parametersString = "") {
  const object = {};
  if (parametersString[0] === "?") {
    parametersString = parametersString.slice(1);
  }
  for (const parameter of parametersString.split("&")) {
    const s = parameter.match(/([^=]+)=?(.*)/) || [];
    if (s.length < 2) {
      continue;
    }
    const key = decodeQueryKey(s[1]);
    if (key === "__proto__" || key === "constructor") {
      continue;
    }
    const value = decodeQueryValue(s[2] || "");
    if (object[key] === undefined) {
      object[key] = value;
    } else if (Array.isArray(object[key])) {
      (object[key]).push(value);
    } else {
      object[key] = [object[key], value];
    }
  }
  return object;
}
const PLUS_RE = /\+/g;
function decodeQueryKey(text) {
  return decode(text.replace(PLUS_RE, " "));
}
function decodeQueryValue(text) {
  return decode(text.replace(PLUS_RE, " "));
}
function decode(text = "") {
  try {
    return decodeURIComponent("" + text);
  } catch {
    return "" + text;
  }
}

// vite
const requestQuerySplitRE = /\?(?!.*[/|}])/
function parseRequest(id){
  const [_, search] = id.split(requestQuerySplitRE, 2)
  if (!search) {
    return null
  }
  return Object.fromEntries(new URLSearchParams(search))
}

const workerRe = /(\?|&)worker(?:&|$)/
const urlRe = /(\?|&)url(?:&|$)/
const rawRe = /(\?|&)raw(?:&|$)/

// data
const urls = [
  '/foo/bar.js',
  '/foo/bar.js?worker',
  '/foo/bar.js?url',
  '/foo/bar.js?worker&url',
  '/foo/bar.js?raw',
  ''
]
  .join('__')
  .repeat(100)
  .split('__')
// ufo test
let a = 0, b = 0, c = 0, d = 0
for (const url of urls) {
  let [_, search] = url.split(requestQuerySplitRE, 2)
  if (!search) continue
  search = '?' + search
  const query = parseQuery(search)
  if (!query) continue
  if (query.worker != null) a++
  else if (query.url != null) b++
  else if (query.raw != null) c++
  else d++
}
console.log(a, b, c, d)
// regex test
let a = 0, b = 0, c = 0, d = 0
for (const url of urls) {
  let [_, search] = url.split(requestQuerySplitRE, 2)
  if (!search) continue
  search = '?' + search
  if (workerRe.test(search)) a++
  else if (urlRe.test(search)) b++
  else if (rawRe.test(search)) c++
  else d++
}
console.log(a, b, c, d)
// parseRequest test
let a = 0, b = 0, c = 0, d = 0
for (const url of urls) {
  const query = parseRequest(url)
  if (!query) continue
  if (query.worker != null) a++
  else if (query.url != null) b++
  else if (query.raw != null) c++
  else d++
}
console.log(a, b, c, d)

The result is that the regex version is roughly 70% faster.

Additional context

I made individual commits removing the usage of parseRequest (note: I messed up the name in the 3rd commit)


What is the purpose of this pull request?

  • Bug fix
  • New Feature
  • Documentation update
  • Other

Before submitting the PR, please make sure you do the following

  • Read the Contributing Guidelines, especially the Pull Request Guidelines.
  • Check that there isn't already a PR that solves the problem the same way to avoid creating a duplicate.
  • Provide a description in this PR that addresses what the PR is solving, or reference the issue that it solves (e.g. fixes #123).
  • Update the corresponding documentation if needed.
  • Ideally, include relevant tests that fail without this PR but pass with it.

@bluwy bluwy added p2-nice-to-have Not breaking anything but nice to have (priority) performance Performance related enhancement labels Jan 16, 2024
Copy link

stackblitz bot commented Jan 16, 2024

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

@bluwy
Copy link
Member Author

bluwy commented Jan 16, 2024

/ecosystem-ci run

@vite-ecosystem-ci
Copy link

📝 Ran ecosystem CI on c9ce9c3: Open

suite result latest scheduled
analogjs success success
astro success success
histoire success failure
ladle success success
laravel failure failure
marko success success
nuxt success success
nx success success
previewjs success success
qwik failure success
rakkas success success
remix failure undefined undefined
sveltekit success success
unocss success failure
vike failure failure
vite-plugin-pwa success success
vite-plugin-react success success
vite-plugin-react-pages success success
vite-plugin-react-swc success success
vite-plugin-svelte success success
vite-plugin-vue success success
vite-setup-catalogue success success
vitepress success failure
vitest success failure

@@ -28,6 +28,10 @@ interface WorkerCache {

export type WorkerType = 'classic' | 'module' | 'ignore'

export const workerOrSharedWorkerRE = /(?:\?|&)(worker|sharedworker)(?:&|$)/
const workerFileRE = /(?:\?|&)worker_file&type=(\w+)(?:&|$)/
Copy link
Member

@patak-dev patak-dev Jan 16, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For reference to others, we already depend on the order of query suffixes in other cases, like in html proxies. See

const htmlProxyRE =

So this should be ok.

Copy link
Member

@patak-dev patak-dev left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice one! 👏🏼

@patak-dev patak-dev merged commit 0cacfad into main Jan 16, 2024
10 checks passed
@patak-dev patak-dev deleted the perf-avoid-parse-request branch January 16, 2024 10:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
p2-nice-to-have Not breaking anything but nice to have (priority) performance Performance related enhancement
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants