Skip to content

Commit

Permalink
Optimize memory allocation in appendRune function (#1988)
Browse files Browse the repository at this point in the history
* Optimize memory allocation in appendRune function

* Add benchmark tests for appendRune function memory allocation

* remove function

* remove old
  • Loading branch information
mateusveloso authored Nov 8, 2023
1 parent d3929ab commit b93c0c8
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
4 changes: 3 additions & 1 deletion types/append.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,9 @@ func appendRune(b []byte, r rune) []byte {
}
l := len(b)
if cap(b)-l < utf8.UTFMax {
b = append(b, make([]byte, utf8.UTFMax)...)
nb := make([]byte, l, 2*l+utf8.UTFMax)
copy(nb, b)
b = nb
}
n := utf8.EncodeRune(b[l:l+utf8.UTFMax], r)
return b[:l+n]
Expand Down
17 changes: 17 additions & 0 deletions types/append_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package types

import (
"testing"
)

func BenchmarkAppendRuneNew(b *testing.B) {
for i := 0; i < b.N; i++ {
b.StopTimer()
s := make([]byte, 0, 1024)
b.StartTimer()

for j := 0; j < 1000000; j++ {
s = appendRune(s, '世')
}
}
}

0 comments on commit b93c0c8

Please sign in to comment.