最近,需要使用 http client 发送数据,网上都说
fasthttp 据说是目前golang性能最好的http库,相对于自带的net/http,性能说是有10倍的提升
让我们压力测试一下,看看结果如何
安装包
go get -u github.com/valyala/fasthttp
写个测试类 util_test.go
package test
import (
"github.com/valyala/fasthttp"
"net/http"
"net/url"
"strconv"
"strings"
"testing"
)
const serverUrl = "http://127.0.0.1:8080/server/v1/test"
// go 自带的net/http
func BenchmarkNetHttp(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err := netHttp(i); err != nil {
b.Log(err)
}
}
b.StopTimer()
}
// fasthttp
func BenchmarkFasthttp(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err := fastHttp(i); err != nil {
b.Log(err)
}
}
b.StopTimer()
}
func netHttp(i int) error{
params := url.Values{}
params.Add("content", strconv.Itoa(i))
if resp, err := http.PostForm(serverUrl, params); err == nil && resp != nil {
defer resp.Body.Close()
} else {
return err
}
return nil
}
// 代码参考:https://studygolang.com/articles/17716
func fastHttp(i int) error{
req := fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(req) // 用完需要释放资源
// 默认是application/x-www-form-urlencoded
req.Header.SetContentType("application/json")
req.Header.SetMethod("POST")
req.SetRequestURI(serverUrl)
// JSON 格式数据:`{"content":"1"}`
requestBody := strings.Builder{}
requestBody.WriteString(`{"content":`)
requestBody.WriteString(strconv.Itoa(i))
requestBody.WriteString("}")
req.SetBody([]byte(requestBody.String()))
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(resp) // 用完需要释放资源
err := fasthttp.Do(req, resp)
return err
}
进入到 util_test.go 所在的目录,执行命令
go test -bench=. -benchmem
-benchmem 可以查看内存分配的次数,知道为什么某些方法性能更优
测试结果:
说明 被测试方法 循环次数 平均耗时 平均使用内存大小 平均内存分配次数 BenchmarkNetHttp-4 5000 285588 ns/op 14627 B/op 99 allocs/op BenchmarkFasthttp-4 20000 94844 ns/op 37 B/op 2 allocs/op
总结:
fasthttp 主要是使用了“池化”的概念,它高性能主要源自于“复用”,占用更少的内存,更少内存的分配次数,节省了大量的资源分配成本。