Skip to content

Commit 5bdd25e

Browse files
authored
mapstr: optimyze Clone (#64)
Reduce the ammount of allocations when using Clone(). name old time/op new time/op delta Clone-8 8.95µs ± 0% 5.51µs ± 0% ~ (p=1.000 n=1+1) name old alloc/op new alloc/op delta Clone-8 4.99kB ± 0% 2.50kB ± 0% ~ (p=1.000 n=1+1) name old allocs/op new allocs/op delta Clone-8 64.0 ± 0% 33.0 ± 0% ~ (p=1.000 n=1+1)
1 parent 8d26323 commit 5bdd25e

File tree

2 files changed

+36
-5
lines changed

2 files changed

+36
-5
lines changed

mapstr/mapstr.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -152,13 +152,13 @@ func (m M) CopyFieldsTo(to M, key string) error {
152152
// Clone returns a copy of the M. It recursively makes copies of inner
153153
// maps.
154154
func (m M) Clone() M {
155-
result := M{}
155+
result := make(M, len(m))
156156

157-
for k, v := range m {
158-
if innerMap, ok := tryToMapStr(v); ok {
159-
v = innerMap.Clone()
157+
for k := range m {
158+
if innerMap, ok := (m[k]).(M); ok {
159+
result[k] = innerMap.Clone()
160160
}
161-
result[k] = v
161+
result[k] = m[k]
162162
}
163163

164164
return result

mapstr/mapstr_test.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -356,6 +356,37 @@ func TestClone(t *testing.T) {
356356
assert.Equal(M{"c31": 1, "c32": 2}, c["c3"])
357357
}
358358

359+
func BenchmarkClone(b *testing.B) {
360+
assert := assert.New(b)
361+
362+
m := M{
363+
"c1": 1,
364+
"c2": 2,
365+
"c3": M{
366+
"c31": 1,
367+
"c32": 2,
368+
"c33": 3,
369+
"c34": 4,
370+
"c35": 5,
371+
"c36": 6,
372+
"c37": 7,
373+
"c38": 8,
374+
"c39": 9,
375+
},
376+
"c4": 4,
377+
"c5": 5,
378+
"c6": 6,
379+
"c7": 7,
380+
"c8": 8,
381+
"c9": 9,
382+
}
383+
384+
for i := 0; i < b.N; i++ {
385+
c := m.Clone()
386+
assert.Equal(m, c)
387+
}
388+
}
389+
359390
func TestString(t *testing.T) {
360391
type io struct {
361392
Input M

0 commit comments

Comments
 (0)