Skip to content
Myr

get-path.ts

This file

Path

benchmarks/utils/src/get-path.ts

66 lines · 2.1 KiB · TypeScript

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than f0b094d point at it.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–66why, one step back
1import { run, group, bench } from 'mitata'
23bench('noop', () => {})45const request = new Request('http://localhost/about/me')67group('getPath', () => {8 bench('slice + indexOf : w/o decodeURI', () => {9 const url = request.url10 const queryIndex = url.indexOf('?', 8)11 return url.slice(url.indexOf('/', 8), queryIndex === -1 ? undefined : queryIndex)12 })1314 bench('regexp : w/o decodeURI', () => {15 const match = request.url.match(/^https?:\/\/[^/]+(\/[^?]*)/)16 return match ? match[1] : ''17 })1819 bench('slice + indexOf', () => {20 const url = request.url21 const queryIndex = url.indexOf('?', 8)22 const path = url.slice(url.indexOf('/', 8), queryIndex === -1 ? undefined : queryIndex)23 return path.includes('%') ? decodeURIComponent(path) : path24 })2526 bench('slice + for-loop + flag', () => {27 const url = request.url28 const start = url.indexOf('/', 8)29 let i = start30 let hasPercentEncoding = false31 for (; i < url.length; i++) {32 const charCode = url.charCodeAt(i)33 if (charCode === 37) {34 // '%'35 hasPercentEncoding = true36 } else if (charCode === 63) {37 // '?'38 break39 }40 }41 return hasPercentEncoding ? decodeURIComponent(url.slice(start, i)) : url.slice(start, i)42 })4344 bench('slice + for-loop + immediate return', () => {45 const url = request.url46 const start = url.indexOf('/', 8)47 let i = start48 for (; i < url.length; i++) {49 const charCode = url.charCodeAt(i)50 if (charCode === 37) {51 // '%'52 // If the path contains percent encoding, use `indexOf()` to find '?' and return the result immediately.53 // Although this is a performance disadvantage, it is acceptable since we prefer cases that do not include percent encoding.54 const queryIndex = url.indexOf('?', i)55 const path = url.slice(start, queryIndex === -1 ? undefined : queryIndex)56 return decodeURI(path.includes('%25') ? path.replace(/%25/g, '%2525') : path)57 } else if (charCode === 63) {58 // '?'59 break60 }61 }62 return url.slice(start, i)63 })64})6566run()