I am writing a tiny router to just route paths like /user/info
without any special regex or variables in the string. My current implementation just looks like
let routes = {
user: {
path: "/user",
routes: {
info: {
path: "/user/info",
routes: {}
}
}
}
};
It then basically treats itself as a linked list and finds object by object name, like routes["user"]["info"]
; Is there some faster way to do routing that I don't know of? I cannot find anything.
In the given code routes["user"]["info"]
is undefined.
Suggestion: You can create a map
for the lookup.
first look for "users" and then its route "info".
I guess no one really understood my question. Anyway, it appears that the fastest way to find a "thing", ie a route such as /user/add
, in JS is to
All of the 5 methods above are the same speed. The fact that a map is as fast as a switch statement of raw strings is amazing. Using object reflection, as known, is unbearably slow. Hooray for whoever created the map! It's also surprising that using numbers with object reflection is really, really slow. Maybe because each number has to be converted to a string key? Not sure.
Anyway, use a map!
Here is my js perf
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.