在现有的 Golang 切片中,高效地修改值的方法是什么?

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

efficient way to change values in existing golang slice?

问题

我有一个结构体的切片,如下所示:

type Car struct {
	name  string
	price int
	color string
}

cars := make([]Car, 0)

切片被填充了值,稍后我想循环遍历切片并再次更改一个特定的值(price)。目前我是这样做的:

for i := range cars {
		cars[i].price = 10
}

我读到过,当处理大的切片时,通过索引访问切片的性能不是很好。从性能的角度来看,是否更好创建第二个切片并复制值,像这样:

newCars := make([]Car, 0)

for _, car := range cars {
	newCar := car
	newCar.price = 10
		
	newCars = append(newCars, newCar)
}
英文:

I have a slice of a struct like:

type Car struct {
	name  string
	price int
	color string
}

cars := make([]Car, 0)

The slice gets filled with values and later I want to loop over the the slice and change one specific value (price) again. Currently I do it like:

for i := range cars {
		cars[i].price = 10
}

I've read that the performance of accessing a slice over it's index isn't great, when dealing with big slices. Would it (performance wise) be better to create a secound slice and copy the values like:

newCars := make([]Car, 0)

for _, car := range cars {
	newCar := car
	newCar.price = 10
		
	newCars = append(newCars, newCar)
}

答案1

得分: 1

我已经阅读到,当处理大的切片时,通过索引访问切片的性能并不好。从性能上来说,创建一个[第二个]切片并复制值是否更好呢?

不是的

切片是在底层数组上的一个[薄]窗口。数组是一个连续的成员块。通过索引访问数组元素的成本微不足道。在底层,只需要进行一些乘法和一个加法运算。

将切片复制到一个新的空切片至少需要进行一次内存分配(可能还需要更多),以及复制内存的操作。

英文:

> I've read that the performance of accessing a slice over it's index isn't great, when dealing with big slices. Would it (performance wise) be better to create a [second] slice and copy the values...

NO.

A slice is a [thin] window on top of an underlying array. An array is a contiguous block of member. The cost of accessing an array element by index is trivial. It's just a bit of multiplication and 1 addition under the covers.

To copy the slice to a new empty slice requires at least one memory allocation (and possible more), plus copying memory.

huangapple
  • 本文由 发表于 2022年2月8日 18:54:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/71032663.html
匿名

发表评论

匿名网友

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

确定