fasthttp为什么比net/http更快?

huangapple go评论71阅读模式
英文:

Why is fasthttp faster than net/http?

问题

一个基于fasthttp的服务器比net/http快10倍。

是哪些实现细节使得fasthttp如此快速?此外,它如何比net/http更好地处理传入请求?

英文:

A fasthttp based server is up to 10 times faster than net/http.

Which implementation details make fasthttp so much faster? Moreover, how does it manage incoming requests better than net/http?

答案1

得分: 46

文章"http implementation fasthttp in golang"来自husobee提到:

嗯,出于几个原因,这是一个更好的实现:

  1. 工作池模型是一个零分配模型,因为工作线程已经初始化并准备好提供服务,而在stdlib实现中,go c.serve()必须为goroutine分配内存。
  1. 工作池模型更容易调整,因为您可以增加/减少能够接受的工作单元数量的缓冲区大小,而不是在stdlib中的“点火并忘记”模型。
  2. 工作池模型允许处理程序通过通道通信与服务器更紧密地连接,例如,如果服务器需要关闭,它将能够比在stdlib实现中更容易地与工作线程通信。
  3. 处理程序函数定义签名更好,因为它只接受一个包含处理程序所需的请求和写入器的上下文。这比标准库要好得多,因为标准库只提供请求和响应写入器...在go1.7中包含上下文到请求中的工作基本上是一个小技巧,以便给人们提供他们真正想要的东西(上下文),而不会破坏任何人。

总的来说,使用工作池模型编写服务器来处理请求要比仅仅为每个请求生成一个“线程”,而没有办法自动限制速率更好。

英文:

The article "http implementation fasthttp in golang" from husobee mentions:

> Well, this is a much better implementation for several reasons:

> 1. The worker pool model is a zero allocation model, as the workers are already initialized and are ready to serve, whereas in the stdlib implementation the go c.serve() has to allocate memory for the goroutine.
2. The worker pool model is easier to tune, as you can increase/decrease the buffer size of the number of work units you are able to accept, versus the fire and and forget model in the stdlib
3. The worker pool model allows for handlers to be more connected with the server through channel communications, if the server needs to shutdown for example, it would be able to more easily communicate with the workers than in the stdlib implementation
4. The handler function definition signature is better, as it takes in only a context which includes both the request and writer needed by the handler. this is HUGELY better than the standard library, as all you get from the stdlib is a request and response writer… The work in go1.7 to include context within the request is pretty much a hack to give people what they really want (context) without breaking anyone.

> Overall it is just better to write a server with a worker pool model for serving requests, as opposed to just spawning a “thread” per request, with no way of throttling out of the box.

huangapple
  • 本文由 发表于 2017年1月13日 13:31:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/41627931.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定