Skip to content

encoding/json: marshaling RawMessage has poor performance #33422

Open
@rittneje

Description

@rittneje

What version of Go are you using (go version)?

$ go version
go version go1.12.6 linux/amd64

Does this issue reproduce with the latest release?

Yes.

What operating system and processor architecture are you using (go env)?

go env Output
$ go env
GOARCH="amd64"
GOBIN=""
GOCACHE="/home/jrittner/.cache/go-build"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/jrittner/go-workspace"
GOPROXY=""
GORACE=""
GOROOT="/home/jrittner/go"
GOTMPDIR=""
GOTOOLDIR="/home/jrittner/go/pkg/tool/linux_amd64"
GCCGO="gccgo"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build506812392=/tmp/go-build -gno-record-gcc-switches"

What did you do?

Ran a benchmark to compare marshaling a json.RawMessage, a string and a []byte.

package jsontest

import (
	"encoding/json"
	"testing"
)

const msg = `{"a":"aaaaaaa","b":{"c":["d","e"]}}`

var benchmarkResult interface{}

func BenchmarkRawMessage(b *testing.B) {
	x := json.RawMessage(msg)
	for i := 0; i < b.N; i++ {
		j, err := json.Marshal(x)
		if err != nil {
			b.Fatal(err)
		}
		benchmarkResult = j
	}
}

func BenchmarkString(b *testing.B) {
	x := msg
	for i := 0; i < b.N; i++ {
		j, err := json.Marshal(x)
		if err != nil {
			b.Fatal(err)
		}
		benchmarkResult = j
	}
}

func BenchmarkBytes(b *testing.B) {
	x := []byte(msg)
	for i := 0; i < b.N; i++ {
		j, err := json.Marshal(x)
		if err != nil {
			b.Fatal(err)
		}
		benchmarkResult = j
	}
}

What did you expect to see?

I expected marshaling a json.RawMessage to have the best performance of the three, since it should be a no-op.

What did you see instead?

It is 2 times slower than marshaling a string, and 3 times slower than marshaling a []byte.

BenchmarkRawMessage-2 1000000 1513 ns/op 232 B/op 7 allocs/op
BenchmarkString-2 2000000 869 ns/op 112 B/op 3 allocs/op
BenchmarkBytes-2 3000000 561 ns/op 128 B/op 3 allocs/op

Metadata

Metadata

Assignees

No one assigned

    Labels

    NeedsDecisionFeedback is required from experts, contributors, and/or the community before a change can be made.Performance

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions