可以将切片用作共享内存吗?

huangapple go评论76阅读模式
英文:

Is it ok to use slices as shared memory?

问题

在这样的构造中使用切片是否可以呢:

type buffer struct {
	values []int
	mutex sync.RWMutex
}

我问这个问题是因为当我们向切片追加元素时,有可能会将切片复制到内存中的新位置。

英文:

Is it ok to use slices in a construction like this:

type buffer struct {
	values []int
	mutex sync.RWMutex
}

I ask because when we append to slice, there is a chance that we will copy the slice to the new place in memory.

答案1

得分: 3

在大多数Go编程中,人们通常会将切片重新赋值给原变量,而不会担心性能问题,因为切片是引用值。

b.values = append(b.values, i)

type buffer struct {
	values []int
	mutex sync.RWMutex
}

func (b *buffer) Append(i int) {
	b.mutex.Lock()
	b.values = append(b.values, i)
	b.mutex.Unlock()
}
英文:

In most Go programming, people will assign slice back without performance concern in case append returns new memory since slices are reference value.

b.values = append(b.values, i)

type buffer struct {
	values []int
	mutex sync.RWMutex
}

func (b *buffer) Append(i int) {
	b.mutex.Lock()
	b.values = append(b.values, i)
	b.mutex.Unlock()
}

huangapple
  • 本文由 发表于 2021年9月9日 14:24:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/69113198.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定