[opt] nazabytes: 优化Buffer的扩容逻辑

pull/6/head
q191201771 3 years ago
parent f4306e28c3
commit aa4df8dd09

4
.gitignore vendored

@ -1,6 +1,7 @@
/pkg/websocket
/pkg/tag
/pkg/nazatime
/pkg/congestion_control
/playground
/playground/cc
@ -10,7 +11,8 @@
/demo/temp
/demo/analyse_git_log
/demo/analyse_wireshark_plain_txt_dissection
/demo/disksweeper/
/demo/disksweeper
/demo/diskbackup
/.idea
/.trash

@ -18,6 +18,7 @@ import (
// TODO(chef): 增加options: growRoundThreshold; 是否做检查
// TODO(chef): 扩容策略函数可由外部传入
const growMinThreshold = 128
const growRoundThreshold = 1048576 // 1MB
// Buffer 先进先出可扩容流式buffer可直接读写内部切片避免拷贝
@ -133,14 +134,16 @@ func (b *Buffer) Grow(n int) {
return
}
// 预分配一些
if n <= growMinThreshold {
n = growMinThreshold
} else if n < growMinThreshold {
n = roundUpPowerOfTwo(n)
}
// 扩容后总共需要的大小
needed := b.Len() + n
// 扩容大小在阈值范围内时向上取值到2的倍数
if needed < growRoundThreshold {
needed = roundUpPowerOfTwo(needed)
}
nazalog.Debugf("[%p] Buffer::Grow. realloc, n=%d, copy=%d, cap=(%d, %d)", b, n, b.Len(), b.Cap(), needed)
core := make([]byte, needed, needed)
copy(core, b.core[b.rpos:b.wpos])

@ -47,9 +47,9 @@ func TestBuffer(t *testing.T) {
assert.Equal(t, golden, buf)
b.Skip(10)
assert.Equal(t, nil, b.Bytes())
assert.Equal(t, 16, len(b.WritableBytes()))
assert.Equal(t, 128, len(b.WritableBytes()))
assert.Equal(t, 0, b.Len())
assert.Equal(t, 16, b.Cap())
assert.Equal(t, 128, b.Cap())
// 利用头部空闲空间扩容
buf = b.ReserveBytes(10)
@ -63,7 +63,7 @@ func TestBuffer(t *testing.T) {
assert.Equal(t, golden[2:], b.Bytes()[:8])
assert.Equal(t, golden[:7], b.Bytes()[8:])
assert.Equal(t, 15, b.Len())
assert.Equal(t, 16, b.Cap())
assert.Equal(t, 128, b.Cap())
// Truncate
b.Reset()

Loading…
Cancel
Save