Golang fasthttpはなぜあなたがこんなに優秀ですか?
最近、http clientを使ってデータを送る必要があります.
fasthttpは現在golangの最高性能を誇るhttpライブラリと言われていますが、持参したnet/httpに対して、性能は10倍にアップしています.
参考:https://studygolang.com/articles/17716
ストレステストをして、結果を見てみましょう.
パッケージをインストール
テスト結果:

説明
被試験方法
サイクル数
平均して時間がかかる
平均使用メモリサイズ
平均メモリ割り当て回数
Benchmark NetHttp-4
5000
285588 ns/op
14627 B/op
99 allocs/op
Benchmark Fasthtp-4
20000
94844 ns/op
37 B/op
2 allocs/op
まとめ:
fasthttpは主に「池化」という概念を使っていますが、その高性能は主に「多重化」に由来しています.メモリの割り当て回数が少なく、大量の資源配分コストが節約されています.
fasthttpは現在golangの最高性能を誇るhttpライブラリと言われていますが、持参したnet/httpに対して、性能は10倍にアップしています.
参考:https://studygolang.com/articles/17716
ストレステストをして、結果を見てみましょう.
パッケージをインストール
go get -u github.com/valyala/fasthttp
テストクラスを書きます utilu.test.gopackage 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
}
に入ります utilu.test.goがいるディレクトリで、命令を実行します.go test -bench=. -benchmem
-benchmem メモリの割り当て回数を確認できます.なぜいくつかの方法がより優れていますか?テスト結果:

説明
被試験方法
サイクル数
平均して時間がかかる
平均使用メモリサイズ
平均メモリ割り当て回数
Benchmark NetHttp-4
5000
285588 ns/op
14627 B/op
99 allocs/op
Benchmark Fasthtp-4
20000
94844 ns/op
37 B/op
2 allocs/op
まとめ:
fasthttpは主に「池化」という概念を使っていますが、その高性能は主に「多重化」に由来しています.メモリの割り当て回数が少なく、大量の資源配分コストが節約されています.