Benchmark: Retrieving Values from Deep Nested JSON at Golang

This sample script is for retrieving values from a deep nested JSON. There are 2 patterns. So for these, the benchmark were measured.

Script :

package main

import (
    "encoding/json"
    "testing"
)

const (
    data = `{
      "A_key1": {
        "B_key1": {
          "C_key": "value"
        }
      }
    }`
)

func BenchmarkB1(b *testing.B) {
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        var p map[string]interface{}
        json.Unmarshal([]byte(data), &p)
        a1 := p["A_key1"]
        a2 := p["A_key1"].(map[string]interface{})["B_key1"]
        a3 := p["A_key1"].(map[string]interface{})["B_key1"].(map[string]interface{})["C_key"]
        _ = a1 // --> map[B_key1:map[C_key:value]]
        _ = a2 // --> map[C_key:value]
        _ = a3 // --> value
    }
}

func BenchmarkB2(b *testing.B) {
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        var p map[string]interface{}
        json.Unmarshal([]byte(data), &p)
        b1 := p["A_key1"]
        temp, _ := json.Marshal(b1)
        json.Unmarshal(temp, &p)
        b2 := p["B_key1"]
        temp, _ = json.Marshal(b2)
        json.Unmarshal(temp, &p)
        b3 := p["C_key"]
        _ = b1 // --> map[B_key1:map[C_key:value]]
        _ = b2 // --> map[C_key:value]
        _ = b3 // --> value
    }
}

Result :

$ go test -bench .
BenchmarkB1-4             300000              4177 ns/op
BenchmarkB2-4             100000             13619 ns/op
PASS

It was found that the process cost of json.Unmarshal() was high. json.Unmarshal() for test 2 is 3 times larger than that for test 1.

 Share!