简体   繁体   English

在JS中找到路线的最快方法是什么?

[英]What's the fastest way to find a route in JS?

I am writing a tiny router to just route paths like /user/info without any special regex or variables in the string. 我正在编写一个小型路由器,仅路由/user/info类的路径,而字符串中没有任何特殊的正则表达式或变量。 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"] ; 然后,它基本上将自己视为链接列表,并按对象名称查找对象,如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. 在给定的代码中, routes["user"]["info"]未定义。

Suggestion: You can create a map for the lookup. 建议:您可以为查找创建一个map

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 无论如何,似乎在JS中找到“事物”(例如/user/add的最快方法是

  1. Use a switch statement of strings 使用字符串的switch语句
  2. Use an if statement of strings 使用字符串的if语句
  3. Use a switch statement of numbers 使用数字的转换语句
  4. Use an if statement of numbers 使用数字if语句
  5. Use a map of strings (wow!) 使用字符串映射(哇!)

All of the 5 methods above are the same speed. 以上5种方法的速度均相同。 The fact that a map is as fast as a switch statement of raw strings is amazing. 映射与原始字符串的switch语句一样快的事实令人惊讶。 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 这是我的js性能

It also seems to scale 它似乎也有规模

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM