Skip to content

Commit

Permalink
improve performance by less data copying
Browse files Browse the repository at this point in the history
  • Loading branch information
Carlos Rodriguez committed Aug 29, 2012
1 parent 8c33d7b commit 874a590
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 16 deletions.
11 changes: 8 additions & 3 deletions lib/item.js
@@ -1,6 +1,6 @@
var currentId = 0
, parseUrl = require('./parseUrl')
, pathRegExp = require('../').pathRegExp
, parseUrl = require('url').parse;

function Item (args, cache) {
this.weight = 0;
Expand Down Expand Up @@ -57,8 +57,13 @@ Item.prototype.match = function(req) {
return true;
}

var reqPath = parseUrl(req.url).pathname
, matches = this.regex.exec(reqPath)
var reqPath = parseUrl(req).pathname;

// Exact match
if (reqPath === this.path) return {};

// Try the regex
var matches = this.regex.exec(reqPath)

if (!matches) return false;
matches.shift();
Expand Down
16 changes: 6 additions & 10 deletions lib/middler.js
@@ -1,4 +1,5 @@
var matcher = require('../').matcher
, parseUrl = require('./parseUrl')
, pathRegExp = require('../').pathRegExp
, Item = require('../').Item

Expand All @@ -20,11 +21,13 @@ Middler.prototype.attach = function (server) {
* Middleware kernel. Embeddable in other middleware!
*/
Middler.prototype.handler = function middlerKernel (req, res, next) {
var runlist = this.runlist()
, thisArg = {req: req, res: res};
var thisArg = {req: req, res: res}
, i = 0
, items = this.items
;

(function nextItem () {
var item = runlist.shift();
var item = items[i++];

if (item) {
var m = item.match(req);
Expand Down Expand Up @@ -133,11 +136,4 @@ Middler.prototype.sort = function () {
return a[prop] < b[prop] ? -1 : 1;
}
this.items.sort(sortProp.bind(null, 'weight'));
};

/**
* Returns a copy of all items.
*/
Middler.prototype.runlist = function () {
return this.items.slice(0);
};
11 changes: 8 additions & 3 deletions lib/parseUrl.js
@@ -1,8 +1,13 @@
var parse = require('url').parse;

// Cached parsed urls.
var cache = {};
module.exports = function parseUrl (req) {
var parsed = req._parsedUrl;

module.exports = function parseUrl (url) {
return cache[url] || (cache[url] = parse(url));
if (parsed && parsed.href == req.url) {
return parsed;
}
else {
return req._parsedUrl = parse(req.url);
}
};

0 comments on commit 874a590

Please sign in to comment.