为什么web的路由url到handllefunc的映射都用的树结构,如果用map[url]func,好处是什么

type ControllerRegister struct { routers map[string]Tree enableFilter bool filters map[int][]FilterRouter pool sync.Pool }

beegod的路由,还有看到的几个web框架也是树,但是用 type HandleMap map[string]HandleFunc

var handleMap HandleMap

type Route struct { Tree map[string]*HandleMap } 也是可以得,因为url是唯一的,问问这样的好处是什么

已邀请:

lnhlg

赞同来自:

楼主这样想太概是认为用map的性能要好一些吧,当初我也是这么想的,做过一个框架就是用的map,发现性能并没有比树更好。

tupunco

赞同来自:

有一个原因是map的key是固定的, 如果碰到有规则匹配的路径就没法做了, 比如/news/:id这样的规则.

Xargin

赞同来自:

之前也看过一点这些路由的实现 猜想用radix tree做字符串匹配应该效率更高一些吧

wiki上有一段radixtree和hashtable的简单比较:

Hash tables are commonly said to have expected O(1) insertion and deletion times, but this is only true when considering computation of the hash of the key to be a constant-time operation. When hashing the key is taken into account, hash tables have expected O(k) insertion and deletion times, but may take longer in the worst case depending on how collisions are handled. Radix trees have worst-case O(k) insertion and deletion. The successor/predecessor operations of radix trees are also not implemented by hash tables.

楼上说的也对,如果你的url里带参数,那User/:number/Order/:number这种map似乎就没法做了

要回复问题请先登录注册