Tăng tốc API của bạn
Tạo các đối tượng mới có thể là một hoạt động tương đối tốn kém, đặc biệt nếu nó liên quan đến việc phân bổ bộ nhớ trên heap, vì vậy, việc sử dụng lại các đối tượng có thể giúp giảm chi phí hoạt động và cải thiện hiệu suất. Bằng cách giữ một nhóm các đối tượng được phân bổ trước và sử dụng lại chúng khi cần, chúng ta có thể tránh được chi phí cấp phát và hủy cấp phát bộ nhớ (trình thu gom rác giải phóng các biến không sử dụng trong bộ nhớ).
Điều này có thể đặc biệt hữu ích đối với các API cần xử lý một số lượng lớn yêu cầu, trong đó việc tạo và hủy các đối tượng trên mỗi yêu cầu có thể là một nút thắt cổ chai đáng kể. Bằng cách sử dụng lại các đối tượng, chúng ta có thể giảm lượng thời gian CPU và bộ nhớ cần thiết, điều này có thể dẫn đến hiệu suất tốt hơn và khả năng xử lý nhiều yêu cầu hơn.
Để đạt được điều này, chúng ta có thể sử dụng sync.Poolgói trong Go để triển khai nhóm đối tượng. Đây sync.Poollà gói Go tích hợp cung cấp cơ chế an toàn cho luồng để lưu trữ và truy xuất các đối tượng từ nhóm.
Có thể nhảy vào mã trực tiếp ..!!
Người xử lý: -
package handlers
import (
"encoding/json"
"net/http"
"sync"
)
type Request struct {
Name string `json:"name"`
Id string `json:"id"`
Country string `json:"country"`
Age int `json:"age"`
}
type ObjectPool struct {
ReqPool *sync.Pool
}
var objPool ObjectPool
func init() {
// init object pool
objPool.ReqPool = &sync.Pool{
New: func() interface{} {
return new(Request)
},
}
}
func HandlerWithoutSyncPool() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
req :=new(Request)
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
err = json.NewEncoder(w).Encode(req)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
})
}
func HandlerWithSyncPool() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
req := objPool.ReqPool.Get().(*Request)
//to make sure it return object to pool
defer objPool.ReqPool.Put(req)
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
})
}
Lưu ý: -kết quả thay đổi theo loại đối tượng chúng tôi đang tổng hợp
package handlers
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)
var tests = []struct {
req Request
}{
{
req: Request{Name: "test", Country: "testCountry", Id: "id1", Age: 10},
},
}
func BenchmarkHandlerWithSyncPool(b *testing.B) {
for _, test := range tests {
data, _ := json.Marshal(test)
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
_, _ = http.Post("http://127.0.0.1:8888/withpool", "application/json", bytes.NewBuffer(data))
}
})
}
}
func BenchmarkHandlerWithoutSyncPool(b *testing.B) {
for _, test := range tests {
data, _ := json.Marshal(test)
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
_, _ = http.Post("http://127.0.0.1:8888/withoutpool", "application/json", bytes.NewBuffer(data))
}
})
}
}
go test -bench=BenchmarkHandlerWithoutSyncPool -benchtime=5s -cpu=1
goos: darwin
goarch: amd64
pkg: testsyncpool/handlers
cpu: Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
BenchmarkHandlerWithoutSyncPool 23067 1004690 ns/op
go test -bench=BenchmarkHandlerWithSyncPool -benchtime=5s -cpu=1
goos: darwin
goarch: amd64
pkg: testsyncpool/handlers
cpu: Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
BenchmarkHandlerWithSyncPool 77290 76521 ns/op
package main
import (
"log"
"net/http"
"net/http/pprof"
"testsyncpool/handlers"
)
func main() {
r := http.NewServeMux()
//r.Handle("/withoutpool", handlers.HandlerWithoutSyncPool())
r.Handle("/withpool", handlers.HandlerWithSyncPool())
// Register pprof handlers
r.HandleFunc("/debug/pprof/", pprof.Index)
r.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
r.HandleFunc("/debug/pprof/profile", pprof.Profile)
r.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
r.HandleFunc("/debug/pprof/trace", pprof.Trace)
err := http.ListenAndServe(":8888", r)
if err != nil {
log.Fatal(err)
}
}
Vui lòng thêm bất kỳ nhận xét/gợi ý/lỗi nào, v.v...

![Dù sao thì một danh sách được liên kết là gì? [Phần 1]](https://post.nghiatu.com/assets/images/m/max/724/1*Xokk6XOjWyIGCBujkJsCzQ.jpeg)



































