英文:
Golang copy elements of object to slice
问题
有没有更好的方法将函数应用于对象的字段,然后将结果复制到一个新的切片中?更好的意思是比使用for循环具有更好的性能。
var tmp []string
for _, value := range some_object.some_field {
tmp = append(tmp, do_something(value))
}
类似于:
tmp := map_copy(do_something(some_object.some_field))
生成的切片如下:
tmp[0] = do_something(some_object.some_value[0])
tmp[1] = do_something(some_object.some_value[1])
tmp[2] = do_something(some_object.some_value[2])
....
<details>
<summary>英文:</summary>
Is there any better way to apply a function to fields of an object and then copy the result to a new slice? By better I mean having a better performance than a for loop.
var tmp []string
for _, value := range some_object.some_field {
tmp = append(tmp, do_something(value))
}
Something like:
tmp := map_copy(do_something(some_object.some_field))
With the resulting slice being:
tmp[0] = do_something(some_object.some_value[0])
tmp[1] = do_something(some_object.some_value[1])
tmp[2] = do_something(some_object.some_value[2])
....
</details>
# 答案1
**得分**: 5
你唯一能增加性能的方法是提前分配正确的切片容量。
你仍然可以通过从长度为0的切片开始使用append来添加值:
tmp := make([]string, 0, len(some_object.some_field))
for _, value := range some_object.some_field {
tmp = append(tmp, do_something(value))
}
或者通过直接索引切片:
tmp := make([]string, len(some_object.some_field))
for i := range some_object.some_field {
tmp[i] = do_something(some_object.some_field[i])
}
<details>
<summary>英文:</summary>
The only performance increase you could add is allocating the correct slice capacity ahead of time.
You can still add values with append by starting with a 0 length slice:
tmp := make([]string, 0, len(some_object.some_field))
for _, value := range some_object.some_field {
tmp = append(tmp, do_something(value))
}
Or by indexing the slices directly:
tmp := make([]string, len(some_object.some_field))
for i := range some_object.some_field {
tmp[i] = do_something(some_object.some_field[i])
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论