lukeed / trouter

:fish: A fast, small-but-mighty, familiar fish...errr, router*
MIT License
634 stars 23 forks source link

Optimization #19

Closed eco747 closed 1 year ago

eco747 commented 2 years ago

Hello, First, thanks for this source code, it's nice :) I think you should optimize method comparison in find function.

  1. create an dictionary with methods names that map to a number:
let mthMap = {
        GET: 1,
    HEAD: 2,    
    PATCH: 3,
    OPTIONS: 4,
    CONNECT: 5,
    DELETE: 6,
    TRACE: 7,
    POST: 8,
    PUT: 9,

    "": 0, // tip, this is ALL
}
  1. add a mthidx to each routes:
add(method, route, ...fns) {
    let { keys, pattern } = parse(route);
    let handlers = [].concat.apply([], fns);
    this.routes.push({ keys, pattern, method, handlers, 
              mthidx:mthMap[method]  // <<< here
        });
    return this;
}
  1. in find, you can now compare numbers:
find(method, url) {
    let mthidx = mthMap[method];
        let isHEAD = (mthidx === 2);

    let i=0, j=0, k, tmp, arr=this.routes;
    let matches=[], params={}, handlers=[];
    for (; i < arr.length; i++) {
        tmp = arr[i];
                // old code
                // if (tmp.method.length === 0 || tmp.method === method || isHEAD && tmp.method === 'GET') {

                // new code
        if (tmp.mthidx === mthidx  || !tmp.mthidx || (isHEAD && tmp.mthidx===1) ) {   
lukeed commented 2 years ago

Hey, thanks – this works for me. Do you want to PR this change?