Golang copy elements of object to slice

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

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>



huangapple
  • 本文由 发表于 2017年4月17日 23:04:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/43454043.html
匿名

发表评论

匿名网友

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

确定