Created
April 27, 2015 20:27
-
-
Save klauspost/0aacfc0cbb9eee99b9db to your computer and use it in GitHub Desktop.
Revised benchmark
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"github.com/pquerna/ffjson/ffjson" | |
"io" | |
"log" | |
"net/http/httptest" | |
"runtime" | |
"testing" | |
) | |
const helloWorldString = "Hello, World!" | |
type Message struct { | |
Message string `json:"message"` | |
} | |
// Without ffjson definitions. | |
// ffjson: skip | |
type XMessage struct { | |
Message string `json:"message"` | |
} | |
func Encode(item interface{}, out io.Writer) { | |
// Encode | |
buf, err := ffjson.Marshal(&item) | |
if err != nil { | |
log.Fatalf("Error: %+v\n", err) | |
} | |
// Write the buffer | |
_, _ = out.Write(buf) | |
// We are now no longer need the buffer so we pool it. | |
ffjson.Pool(buf) | |
} | |
func encoderFunction(b *testing.B) { | |
m := &XMessage{helloWorldString} | |
for i := 0; i < b.N; i++ { | |
w := httptest.NewRecorder() | |
err := json.NewEncoder(w).Encode(m) | |
if err != nil { | |
panic(err) | |
} | |
} | |
} | |
func ffencoderFunction(b *testing.B) { | |
m := &Message{helloWorldString} | |
for i := 0; i < b.N; i++ { | |
w := httptest.NewRecorder() | |
err := ffjson.NewEncoder(w).EncodeFast(m) | |
if err != nil { | |
panic(err) | |
} | |
} | |
} | |
func marshalFunction(b *testing.B) { | |
m := &XMessage{helloWorldString} | |
for i := 0; i < b.N; i++ { | |
w := httptest.NewRecorder() | |
a, err := json.Marshal(m) | |
if err != nil { | |
panic(err) | |
} | |
w.Write(a) | |
} | |
} | |
func ffmarshalFunction(b *testing.B) { | |
m := &Message{helloWorldString} | |
for i := 0; i < b.N; i++ { | |
w := httptest.NewRecorder() | |
a, err := ffjson.MarshalFast(m) | |
if err != nil { | |
panic(err) | |
} | |
w.Write(a) | |
ffjson.Pool(a) | |
} | |
} | |
func main() { | |
// numProcs := runtime.NumCPU() | |
numProcs := 1 | |
runtime.GOMAXPROCS(numProcs) | |
log.Println("GOMAXPROCS: ", numProcs) | |
mf := testing.Benchmark(marshalFunction) | |
ffef := testing.Benchmark(ffencoderFunction) | |
ef := testing.Benchmark(encoderFunction) | |
ffmf := testing.Benchmark(ffmarshalFunction) | |
fmt.Println("encoding/json Marshal Function: ", mf) | |
fmt.Println("ffjson Marshal Function: ", ffmf) | |
fmt.Println("") | |
fmt.Println("encoding/json Encoder Function: ", ef) | |
fmt.Println("ffjson Encoder Function: ", ffef) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment