diff --git a/.gitignore b/.gitignore index 8ea2fc8..defffe1 100644 --- a/.gitignore +++ b/.gitignore @@ -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 diff --git a/pkg/nazabytes/buffer.go b/pkg/nazabytes/buffer.go index 30ee3a8..3ac14d9 100644 --- a/pkg/nazabytes/buffer.go +++ b/pkg/nazabytes/buffer.go @@ -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]) diff --git a/pkg/nazabytes/buffer_test.go b/pkg/nazabytes/buffer_test.go index 68310e4..1368f33 100644 --- a/pkg/nazabytes/buffer_test.go +++ b/pkg/nazabytes/buffer_test.go @@ -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()