Skip to content

Commit

Permalink
perf(utils/url): use slice + indexOf for getPath() (#2376)
Browse files Browse the repository at this point in the history
* perf(utils/url): use `slice` + `indexOf` for `getPath()`

* denoify
  • Loading branch information
yusukebe authored Mar 18, 2024
1 parent c2a2136 commit e675d50
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 6 deletions.
2 changes: 2 additions & 0 deletions benchmarks/utils/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
yarn.lock
bun.lockb
5 changes: 5 additions & 0 deletions benchmarks/utils/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"devDependencies": {
"mitata": "^0.1.11"
}
}
20 changes: 20 additions & 0 deletions benchmarks/utils/src/get-path.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { run, group, bench } from 'mitata'

bench('noop', () => {})

const request = new Request('http://localhost/about/me')

group('getPath', () => {
bench('slice + indexOf', () => {
const url = request.url
const queryIndex = url.indexOf('?', 8)
url.slice(url.indexOf('/', 8), queryIndex === -1 ? undefined : queryIndex)
})

bench('regexp', () => {
const match = request.url.match(/^https?:\/\/[^/]+(\/[^?]*)/)
match ? match[1] : ''
})
})

run()
7 changes: 4 additions & 3 deletions deno_dist/utils/url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,10 @@ export const getPattern = (label: string): Pattern | null => {
}

export const getPath = (request: Request): string => {
// Optimized: RegExp is faster than indexOf() + slice()
const match = request.url.match(/^https?:\/\/[^/]+(\/[^?]*)/)
return match ? match[1] : ''
// Optimized: indexOf() + slice() is faster than RegExp
const url = request.url
const queryIndex = url.indexOf('?', 8)
return url.slice(url.indexOf('/', 8), queryIndex === -1 ? undefined : queryIndex)
}

export const getQueryStrings = (url: string): string => {
Expand Down
7 changes: 4 additions & 3 deletions src/utils/url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,10 @@ export const getPattern = (label: string): Pattern | null => {
}

export const getPath = (request: Request): string => {
// Optimized: RegExp is faster than indexOf() + slice()
const match = request.url.match(/^https?:\/\/[^/]+(\/[^?]*)/)
return match ? match[1] : ''
// Optimized: indexOf() + slice() is faster than RegExp
const url = request.url
const queryIndex = url.indexOf('?', 8)
return url.slice(url.indexOf('/', 8), queryIndex === -1 ? undefined : queryIndex)
}

export const getQueryStrings = (url: string): string => {
Expand Down

0 comments on commit e675d50

Please sign in to comment.