type T2 struct {
T string
}
+ type T3 struct {
+ X float64
+ Z *int
+ }
s1 := "string1"
s2 := "string2"
type T1 struct {
A, B, C int
M map[string]*float64
+ M2 map[int]T3
EmptyMap map[string]int // to check that we receive a non-nil map.
N *[3]float64
Strs *[2]string
}
pi := 3.14159
e := 2.71828
+ meaning := 42
+ fingers := 5
t1 := &T1{
A: 17,
B: 18,
C: -5,
M: map[string]*float64{"pi": &pi, "e": &e},
+ M2: map[int]T3{4: T3{X: pi, Z: &meaning}, 10: T3{X: e, Z: &fingers}},
EmptyMap: make(map[string]int),
N: &[3]float64{1.5, 2.5, 3.5},
Strs: &[2]string{s1, s2},
}
// decodeIntoValue is a helper for map decoding.
-func decodeIntoValue(state *decoderState, op decOp, isPtr bool, value reflect.Value, ovfl error) reflect.Value {
- instr := &decInstr{op, 0, nil, ovfl}
+func decodeIntoValue(state *decoderState, op decOp, isPtr bool, value reflect.Value, instr *decInstr) reflect.Value {
v := value
if isPtr {
v = decAlloc(value)
}
+
op(instr, state, v)
return value
}
n := int(state.decodeUint())
keyIsPtr := mtyp.Key().Kind() == reflect.Ptr
elemIsPtr := mtyp.Elem().Kind() == reflect.Ptr
+ keyInstr := &decInstr{keyOp, 0, nil, ovfl}
+ elemInstr := &decInstr{elemOp, 0, nil, ovfl}
for i := 0; i < n; i++ {
- key := decodeIntoValue(state, keyOp, keyIsPtr, allocValue(mtyp.Key()), ovfl)
- elem := decodeIntoValue(state, elemOp, elemIsPtr, allocValue(mtyp.Elem()), ovfl)
+ key := decodeIntoValue(state, keyOp, keyIsPtr, allocValue(mtyp.Key()), keyInstr)
+ elem := decodeIntoValue(state, elemOp, elemIsPtr, allocValue(mtyp.Elem()), elemInstr)
value.SetMapIndex(key, elem)
}
}
}
}
}
+
+func BenchmarkDecodeMap(b *testing.B) {
+ count := 10000
+ m := make(map[int]int, count)
+ for i := 0; i < count; i++ {
+ m[i] = i
+ }
+ var buf bytes.Buffer
+ enc := NewEncoder(&buf)
+ err := enc.Encode(m)
+ if err != nil {
+ b.Fatal(err)
+ }
+ bbuf := benchmarkBuf{data: buf.Bytes()}
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ rm := make(map[int]int, 0)
+ bbuf.reset()
+ dec := NewDecoder(&bbuf)
+ err := dec.Decode(&rm)
+ if err != nil {
+ b.Fatal(i, err)
+ }
+ }
+}