gpt4 book ai didi

go - 将 slice 扩展到其容量的最简单方法是什么?

转载 作者:IT王子 更新时间:2023-10-29 01:23:06 27 4
gpt4 key购买 nike

我有一个程序使用缓冲池来减少代码中一些性能敏感部分的分配。

是这样的:play link

// some file or any data source
var r io.Reader = bytes.NewReader([]byte{1,2,3})

// initialize slice to max expected capacity
dat := make([]byte, 20)

// read some data into it. Trim to length.
n, err := r.Read(dat)
handle(err)
dat = dat[:n]

// now I want to reuse it:
for len(dat) < cap(dat) {
dat = append(dat, 0)
}

log.Println(len(dat))
// add it to free list for reuse later
// bufferPool.Put(dat)

我总是分配固定长度的 slice ,保证大于所需的最大大小。我需要将大小减小到实际数据长度以使用缓冲区,但我还需要它再次成为最大大小以便在下次需要时读入它。

我知道的扩展 slice 的唯一方法是使用 append,所以这就是我正在使用的方法。虽然循环感觉 super 脏。并且可能效率低下。我的基准测试表明它并不可怕,但我觉得必须有更好的方法。

我对 slice 的内部表示知之甚少,但如果我能以某种方式覆盖长度值而不实际添加数据,那就太好了。我真的不需要将它归零或做任何事情。

有没有更好的方法来完成这个?

最佳答案

“扩展”一个 slice 到它的容量只是一个 slice expression , 并将容量指定为高索引。高索引不需要小于长度。限制是:

For arrays or strings, the indices are in range if 0 <= low <= high <= len(a), otherwise they are out of range. For slices, the upper index bound is the slice capacity cap(a) rather than the length.

例子:

b := make([]byte, 10, 20)
fmt.Println(len(b), cap(b), b)

b = b[:cap(b)]
fmt.Println(len(b), cap(b), b)

输出(在 Go Playground 上尝试):

10 20 [0 0 0 0 0 0 0 0 0 0]
20 20 [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]

关于go - 将 slice 扩展到其容量的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46346077/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com