Gin 是一个用 Go 编写的 Web 框架。它具有类似马提尼酒的 API,由于 httprouter,性能最高可提高 40 倍。
那是他们在 Gin 框架主页上所说的。我很好奇他们采用了哪一部分和什么技术来使速度提高 40 倍。
在我的理解中,在任何网络框架中处理请求的方式都是相似的。
我不知道这是否正确,但我认为多路复用器是不同 Web 服务器(框架)之间唯一的速度差异。
golang标准库中默认的multiplexer定义如下,使用hash table查找handler。
type ServeMux struct {
mu sync.RWMutex
m map[string]muxEntry
es []muxEntry // slice of entries sorted from longest to shortest.
hosts bool // whether any patterns contain hostnames
}
type muxEntry struct {
h Handler
pattern string
}
httprouter 使用基数树,定义为
type Router struct {
trees map[string]*node
...
}
type node struct {
path string
wildChild bool
nType nodeType
maxParams uint8
priority uint32
indices string
children []*node
handle Handle
}
那么问题来了:既然都是用hash table来找handler或者radix tree的一个节点,为什么httprouter跑得更快?他们是用什么方法制作的?