Go 优先队列 – 分配子切片

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

Go priority queues - assigning a sub-slice

问题

我正在阅读Go标准库中的优先队列这里,并且我正在看这段代码:

func (pq *PriorityQueue) Pop() interface{} {
    old := *pq
    n := len(old)
    item := old[n-1]
    old[n-1] = nil  // 避免内存泄漏
    item.index = -1 // 为了安全起见
    *pq = old[0 : n-1]
    return item
}

我对从优先队列中弹出元素的这种方法有些担忧。我知道在这个例子中,PriorityQueue类型是一个指针切片,切片是引用类型,所以old := *pq只是将切片的引用赋值给了old,并没有实际复制任何内容,但是*pq = old[0 : n-1]这一行代码是做什么的?它是创建了另一个切片,还是只是复制了一个引用,将起始和结束索引设置为0n-1

我想在可能有大量元素的优先队列中使用这个类,并且我想避免不必要的复制。

英文:

I'm reading priority queues in the Go standard library here and I'm looking at this code

func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	old[n-1] = nil  // avoid memory leak
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

I'm somewhat concerned about this method of popping elements from a priority queue.. I know that a PriorityQueue type is a slice of pointers in that example and that a slice is a reference type so old := *pq only assigns the reference to the slice and doesn't actually copy anything, but what does the line *pq = old[0 : n-1] do? Does it create another slice or just copies a reference of the old slice with the begin-end indices set to 0 and n-1?

I'd like to use this class for a priority queue with potentially lots and lots of items and I'd like to avoid unnecessary copies.

答案1

得分: 0

old := *pq 会复制 pq 指向的内容。

复制切片会进行浅拷贝 - 复制的切片与原始切片共享同一个数组。

*pq = old[0 : n-1] 创建一个比原始切片短 1 个元素的新切片,并与原始切片共享同一个数组。

复制切片的成本较低,而复制底层数组的成本较高。

在使用切片时,强烈建议阅读:Go 切片:用法和内部原理

英文:

old := *pq makes a copy of whatever pq is pointing at.

Copying a slice makes a shallow copy - the copy is backed by the same array as the original slice.

*pq = old[0 : n-1] creates a new slice that is 1 element shorter and is backed by the same array.

Copying a slice is cheap, copying the backing array is expensive.

Mandatory read when working with slices: Go Slices: usage and internals

huangapple
  • 本文由 发表于 2021年12月3日 19:04:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/70213299.html
匿名

发表评论

匿名网友

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

确定