Skip to content

Swap json.Unmarshal with jsoniter.Unmarshal #315

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion cspell.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@
"testid",
"tokenprovider",
"typecheck",
"uplot"
"uplot",
"bestmemjson",
"jsoniter"
],
"language": "en-US"
}
22 changes: 22 additions & 0 deletions pkg/bestmemjson/bestmemjson.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Package bestmemjson provides JSON operations using the most memory-efficient implementation
// based on benchmark testing. It uses encoding/json for Marshal operations and
// jsoniter for Unmarshal operations.
package bestmemjson

import (
"encoding/json"

jsoniter "github.com/json-iterator/go"
)

// Marshal encodes the input using encoding/json Marshal which uses less memory
// than jsoniter for Marshal operations (112B vs 120B per op)
func Marshal(v interface{}) ([]byte, error) {

Check failure on line 14 in pkg/bestmemjson/bestmemjson.go

View workflow job for this annotation

GitHub Actions / CI / Test and build plugin

use-any: since Go 1.18 'interface{}' can be replaced by 'any' (revive)
return json.Marshal(v)
}

// Unmarshal decodes the input using jsoniter Unmarshal which uses less memory
// than encoding/json for Unmarshal operations (200B vs 352B per op)
func Unmarshal(data []byte, v interface{}) error {

Check failure on line 20 in pkg/bestmemjson/bestmemjson.go

View workflow job for this annotation

GitHub Actions / CI / Test and build plugin

use-any: since Go 1.18 'interface{}' can be replaced by 'any' (revive)
return jsoniter.Unmarshal(data, v)
}
127 changes: 127 additions & 0 deletions pkg/bestmemjson/bestmemjson_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
package bestmemjson

import (
"encoding/json"
"testing"

jsoniter "github.com/json-iterator/go"
"github.com/stretchr/testify/assert"
)

type testStruct struct {
String string `json:"string"`
Number int `json:"number"`
Boolean bool `json:"boolean"`
Array []int `json:"array"`
}

var testJSON = []byte(`{
"string": "test string",
"number": 42,
"boolean": true,
"array": [1, 2, 3, 4, 5]
}`)

var testData = &testStruct{
String: "test string",
Number: 42,
Boolean: true,
Array: []int{1, 2, 3, 4, 5},
}

func TestBestMemJSONEfficiency(t *testing.T) {
t.Run("Marshal memory efficiency", func(t *testing.T) {
// Create sub-benchmarks to measure memory
standardResult := testing.Benchmark(func(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_, _ = json.Marshal(testData)
}
})

jsoniterResult := testing.Benchmark(func(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_, _ = jsoniter.Marshal(testData)
}
})

bestMemResult := testing.Benchmark(func(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_, _ = Marshal(testData)
}
})

// Print the actual memory usage for verification
t.Logf("Memory usage per operation:\n"+
"encoding/json: %d bytes/op, %d allocs/op\n"+
"jsoniter: %d bytes/op, %d allocs/op\n"+
"bestmemjson: %d bytes/op, %d allocs/op",
standardResult.AllocedBytesPerOp(),
standardResult.AllocsPerOp(),
jsoniterResult.AllocedBytesPerOp(),
jsoniterResult.AllocsPerOp(),
bestMemResult.AllocedBytesPerOp(),
bestMemResult.AllocsPerOp())

// Verify bestmemjson is using the most memory-efficient implementation
assert.LessOrEqual(t, bestMemResult.AllocedBytesPerOp(), standardResult.AllocedBytesPerOp(),
"bestmemjson.Marshal should not use more memory than encoding/json.Marshal")
assert.LessOrEqual(t, bestMemResult.AllocedBytesPerOp(), jsoniterResult.AllocedBytesPerOp(),
"bestmemjson.Marshal should not use more memory than jsoniter.Marshal")
})

t.Run("Unmarshal memory efficiency", func(t *testing.T) {
var standardModel, jsoniterModel, bestMemModel testStruct

standardResult := testing.Benchmark(func(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = json.Unmarshal(testJSON, &standardModel)
}
})

jsoniterResult := testing.Benchmark(func(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = jsoniter.Unmarshal(testJSON, &jsoniterModel)
}
})

bestMemResult := testing.Benchmark(func(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = Unmarshal(testJSON, &bestMemModel)
}
})

// Print the actual memory usage for verification
t.Logf("Memory usage per operation:\n"+
"encoding/json: %d bytes/op, %d allocs/op\n"+
"jsoniter: %d bytes/op, %d allocs/op\n"+
"bestmemjson: %d bytes/op, %d allocs/op",
standardResult.AllocedBytesPerOp(),
standardResult.AllocsPerOp(),
jsoniterResult.AllocedBytesPerOp(),
jsoniterResult.AllocsPerOp(),
bestMemResult.AllocedBytesPerOp(),
bestMemResult.AllocsPerOp())

// Verify bestmemjson is using the most memory-efficient implementation
assert.LessOrEqual(t, bestMemResult.AllocedBytesPerOp(), standardResult.AllocedBytesPerOp(),
"bestmemjson.Unmarshal should not use more memory than encoding/json.Unmarshal")
assert.LessOrEqual(t, bestMemResult.AllocedBytesPerOp(), jsoniterResult.AllocedBytesPerOp(),
"bestmemjson.Unmarshal should not use more memory than jsoniter.Unmarshal")

// Verify all implementations produce the same result
assert.Equal(t, standardModel, bestMemModel, "bestmemjson.Unmarshal should produce same result as encoding/json")
assert.Equal(t, jsoniterModel, bestMemModel, "bestmemjson.Unmarshal should produce same result as jsoniter")
})
}
4 changes: 2 additions & 2 deletions pkg/googlesheets/datasource.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ package googlesheets

import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"

"github.com/grafana/google-sheets-datasource/pkg/bestmemjson"
"github.com/grafana/google-sheets-datasource/pkg/models"

"github.com/grafana/grafana-plugin-sdk-go/backend"
Expand Down Expand Up @@ -123,7 +123,7 @@ func writeResult(rw http.ResponseWriter, path string, val any, err error) {
response[path] = val
}

body, err := json.Marshal(response)
body, err := bestmemjson.Marshal(response)
if err != nil {
body = []byte(err.Error())
code = http.StatusInternalServerError
Expand Down
4 changes: 2 additions & 2 deletions pkg/models/query.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package models

import (
"encoding/json"
"fmt"

"github.com/grafana/google-sheets-datasource/pkg/bestmemjson"

Check failure on line 6 in pkg/models/query.go

View workflow job for this annotation

GitHub Actions / CI / Test and build plugin

File is not properly formatted (goimports)
"github.com/grafana/grafana-plugin-sdk-go/backend"
)

Expand All @@ -23,7 +23,7 @@
func GetQueryModel(query backend.DataQuery) (*QueryModel, error) {
model := &QueryModel{}

err := json.Unmarshal(query.JSON, &model)
err := bestmemjson.Unmarshal(query.JSON, &model)
if err != nil {
return nil, fmt.Errorf("error reading query: %s", err.Error())
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/models/settings.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package models

import (
"encoding/json"
"fmt"

"github.com/grafana/google-sheets-datasource/pkg/bestmemjson"

Check failure on line 6 in pkg/models/settings.go

View workflow job for this annotation

GitHub Actions / CI / Test and build plugin

File is not properly formatted (goimports)
"github.com/grafana/grafana-google-sdk-go/pkg/utils"
"github.com/grafana/grafana-plugin-sdk-go/backend"
)
Expand All @@ -29,7 +29,7 @@
model := &DatasourceSettings{}

settings := ctx.DataSourceInstanceSettings
err := json.Unmarshal(settings.JSONData, &model)
err := bestmemjson.Unmarshal(settings.JSONData, &model)
if err != nil {
return nil, fmt.Errorf("error reading settings: %s", err.Error())
}
Expand Down
Loading