소스 검색

fasthttp: shave off a memory allocation in json benchmark

Aliaksandr Valialkin 9 년 전
부모
커밋
919270d181
2개의 변경된 파일24개의 추가작업 그리고 4개의 파일을 삭제
  1. 12 2
      frameworks/Go/fasthttp-mysql/src/hello/hello.go
  2. 12 2
      frameworks/Go/fasthttp-postgresql/src/hello/hello.go

+ 12 - 2
frameworks/Go/fasthttp-mysql/src/hello/hello.go

@@ -12,6 +12,7 @@ import (
 	"os/exec"
 	"runtime"
 	"sort"
+	"sync"
 	"sync/atomic"
 	"time"
 
@@ -20,7 +21,7 @@ import (
 	"github.com/valyala/fasthttp/reuseport"
 )
 
-type Message struct {
+type JSONResponse struct {
 	Message string `json:"message"`
 }
 
@@ -131,7 +132,16 @@ func mainHandler(ctx *fasthttp.RequestCtx) {
 
 // Test 1: JSON serialization
 func jsonHandler(ctx *fasthttp.RequestCtx) {
-	jsonMarshal(ctx, &Message{helloWorldString})
+	r := jsonResponsePool.Get().(*JSONResponse)
+	r.Message = helloWorldString
+	jsonMarshal(ctx, r)
+	jsonResponsePool.Put(r)
+}
+
+var jsonResponsePool = &sync.Pool{
+	New: func() interface{} {
+		return &JSONResponse{}
+	},
 }
 
 // Test 2: Single database query

+ 12 - 2
frameworks/Go/fasthttp-postgresql/src/hello/hello.go

@@ -12,6 +12,7 @@ import (
 	"os/exec"
 	"runtime"
 	"sort"
+	"sync"
 	"sync/atomic"
 	"time"
 
@@ -20,7 +21,7 @@ import (
 	"github.com/valyala/fasthttp/reuseport"
 )
 
-type Message struct {
+type JSONResponse struct {
 	Message string `json:"message"`
 }
 
@@ -122,7 +123,16 @@ func mainHandler(ctx *fasthttp.RequestCtx) {
 
 // Test 1: JSON serialization
 func jsonHandler(ctx *fasthttp.RequestCtx) {
-	jsonMarshal(ctx, &Message{helloWorldString})
+	r := jsonResponsePool.Get().(*JSONResponse)
+	r.Message = helloWorldString
+	jsonMarshal(ctx, r)
+	jsonResponsePool.Put(r)
+}
+
+var jsonResponsePool = &sync.Pool{
+	New: func() interface{} {
+		return &JSONResponse{}
+	},
 }
 
 // Test 2: Single database query