Skip to content

Commit

Permalink
mapstr: optimyze Clone (#64)
Browse files Browse the repository at this point in the history
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)
  • Loading branch information
florianl authored Jun 28, 2022
1 parent 8d26323 commit 5bdd25e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 5 deletions.
10 changes: 5 additions & 5 deletions mapstr/mapstr.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,13 +152,13 @@ func (m M) CopyFieldsTo(to M, key string) error {
// Clone returns a copy of the M. It recursively makes copies of inner
// maps.
func (m M) Clone() M {
result := M{}
result := make(M, len(m))

for k, v := range m {
if innerMap, ok := tryToMapStr(v); ok {
v = innerMap.Clone()
for k := range m {
if innerMap, ok := (m[k]).(M); ok {
result[k] = innerMap.Clone()
}
result[k] = v
result[k] = m[k]
}

return result
Expand Down
31 changes: 31 additions & 0 deletions mapstr/mapstr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,37 @@ func TestClone(t *testing.T) {
assert.Equal(M{"c31": 1, "c32": 2}, c["c3"])
}

func BenchmarkClone(b *testing.B) {
assert := assert.New(b)

m := M{
"c1": 1,
"c2": 2,
"c3": M{
"c31": 1,
"c32": 2,
"c33": 3,
"c34": 4,
"c35": 5,
"c36": 6,
"c37": 7,
"c38": 8,
"c39": 9,
},
"c4": 4,
"c5": 5,
"c6": 6,
"c7": 7,
"c8": 8,
"c9": 9,
}

for i := 0; i < b.N; i++ {
c := m.Clone()
assert.Equal(m, c)
}
}

func TestString(t *testing.T) {
type io struct {
Input M
Expand Down

0 comments on commit 5bdd25e

Please # to comment.