API 속도 향상

Feb 21 2023
새 개체를 만드는 작업은 특히 힙에 메모리를 할당하는 경우 상대적으로 비용이 많이 드는 작업일 수 있으므로 개체를 재사용하면 오버헤드를 줄이고 성능을 향상하는 데 도움이 될 수 있습니다. 미리 할당된 개체 풀을 유지하고 필요에 따라 재사용함으로써 메모리 할당 및 할당 해제(가비지 수집기가 메모리에서 사용하지 않는 변수 할당 해제)의 오버헤드를 피할 수 있습니다.

새 개체를 만드는 작업은 특히 힙에 메모리를 할당하는 경우 상대적으로 비용이 많이 드는 작업일 수 있으므로 개체를 재사용하면 오버헤드를 줄이고 성능을 향상하는 데 도움이 될 수 있습니다. 미리 할당된 개체 풀을 유지하고 필요에 따라 재사용함으로써 메모리 할당 및 할당 해제(가비지 수집기가 메모리에서 사용하지 않는 변수 할당 해제)의 오버헤드를 피할 수 있습니다.

이는 많은 수의 요청을 처리해야 하는 API에 특히 유용할 수 있으며 각 요청에 대한 개체 생성 및 소멸이 상당한 병목 현상이 될 수 있습니다. 개체를 재사용하면 필요한 CPU 시간과 메모리를 줄일 수 있으므로 성능이 향상되고 더 많은 요청을 처리할 수 있습니다.

이를 달성하기 위해 sync.PoolGo의 패키지를 사용하여 객체 풀링을 구현할 수 있습니다. 는 sync.Pool풀에서 개체를 저장하고 검색하기 위한 스레드로부터 안전한 메커니즘을 제공하는 기본 제공 Go 패키지입니다.
바로 코드로 점프할 수 있습니다..!!

핸들러:-


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)
  
 })
}

참고: 결과는 풀링하는 개체 유형에 따라 다릅니다.

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)
 }
}

의견/제안/오류 등을 자유롭게 추가해 주세요…