Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf(mcache): no alloc #227

Merged
merged 1 commit into from
Aug 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 19 additions & 5 deletions lang/mcache/mcache.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package mcache

import (
"sync"
"unsafe"

"github.com/bytedance/gopkg/lang/dirtmake"
)
Expand All @@ -25,12 +26,19 @@ const maxSize = 46
// index contains []byte which cap is 1<<index
var caches [maxSize]sync.Pool

type bytesHeader struct {
Data *byte
Len int
Cap int
}

func init() {
for i := 0; i < maxSize; i++ {
size := 1 << i
caches[i].New = func() interface{} {
buf := dirtmake.Bytes(0, size)
return buf
h := (*bytesHeader)(unsafe.Pointer(&buf))
return h.Data
}
}
}
Expand All @@ -57,8 +65,14 @@ func Malloc(size int, capacity ...int) []byte {
if len(capacity) > 0 && capacity[0] > size {
c = capacity[0]
}
var ret = caches[calcIndex(c)].Get().([]byte)
ret = ret[:size]

i := calcIndex(c)

ret := []byte{}
h := (*bytesHeader)(unsafe.Pointer(&ret))
h.Len = size
h.Cap = 1 << i
h.Data = caches[i].Get().(*byte)
return ret
}

Expand All @@ -68,6 +82,6 @@ func Free(buf []byte) {
if !isPowerOfTwo(size) {
return
}
buf = buf[:0]
caches[bsr(size)].Put(buf)
h := (*bytesHeader)(unsafe.Pointer(&buf))
caches[bsr(size)].Put(h.Data)
}
2 changes: 1 addition & 1 deletion lang/mcache/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,5 @@ func bsr(x int) int {
}

func isPowerOfTwo(x int) bool {
return (x & (-x)) == x
return (x != 0) && ((x & (-x)) == x)
}
Loading