Skip to content

Commit

Permalink
Avoid try catch for a 5x speedup.
Browse files Browse the repository at this point in the history
  • Loading branch information
mcollina committed Jul 4, 2017
1 parent 5734a60 commit acd4547
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
const assert = require('assert')
const Node = require('./node')
const httpMethods = ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT', 'OPTIONS', 'TRACE', 'CONNECT']
var errored = false

function Router (opts) {
if (!(this instanceof Router)) {
Expand Down Expand Up @@ -147,6 +148,7 @@ Router.prototype.lookup = function (req, res) {
Router.prototype.find = function (method, path) {
var currentNode = this.tree
var node = null
var decoded = null
var pindex = 0
var params = []
var pathLen = 0
Expand Down Expand Up @@ -199,23 +201,23 @@ Router.prototype.find = function (method, path) {
currentNode = node
i = 0
while (i < pathLen && path.charCodeAt(i) !== 47) i++
try {
params[pindex++] = decodeURIComponent(path.slice(0, i))
} catch (e) {
decoded = fastDecode(path.slice(0, i))
if (errored) {
return null
}
params[pindex++] = decoded
path = path.slice(i)
continue
}

// wildcard route
node = currentNode.findByKind(2)
if (node) {
try {
params[pindex] = decodeURIComponent(path)
} catch (e) {
decoded = fastDecode(path)
if (errored) {
return null
}
params[pindex] = decoded
currentNode = node
path = ''
continue
Expand Down Expand Up @@ -286,3 +288,12 @@ function sanitizeUrl (url) {
}
return url
}

function fastDecode (path) {
errored = false
try {
return decodeURIComponent(path)
} catch (err) {
errored = true
}
}

0 comments on commit acd4547

Please sign in to comment.