英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论