Go 戈朗海螺多片
我正在尝试合并多个切片,如下所示Go 戈朗海螺多片,go,Go,我正在尝试合并多个切片,如下所示 package routes import ( "net/http" ) type Route struct { Name string Method string Pattern string Secured bool HandlerFunc http.HandlerFunc } type Routes []Route var ApplicationRoutes R
package routes
import (
"net/http"
)
type Route struct {
Name string
Method string
Pattern string
Secured bool
HandlerFunc http.HandlerFunc
}
type Routes []Route
var ApplicationRoutes Routes
func init() {
ApplicationRoutes = append(
WifiUserRoutes,
WifiUsageRoutes,
WifiLocationRoutes,
DashboardUserRoutes,
DashoardAppRoutes,
RadiusRoutes,
AuthenticationRoutes...
)
}
但是,内置的append()能够追加两个片,因此它在编译时抛出了太多的参数来追加。是否有替代功能来完成任务?还是有更好的方法合并切片?
append
对单个元素而不是整个切片进行操作。在循环中追加每个切片
routes := []Routes{
WifiUserRoutes,
WifiUsageRoutes,
WifiLocationRoutes,
DashboardUserRoutes,
DashoardAppRoutes,
RadiusRoutes,
AuthenticationRoutes,
}
var ApplicationRoutes []Route
for _, r := range routes {
ApplicationRoutes = append(ApplicationRoutes, r...)
}
这个问题已经得到了回答,但我想把它贴在这里,因为被接受的答案不是最有效的 原因是创建一个空切片然后追加可能会导致许多不必要的分配 最有效的方法是预先分配一个切片并将元素复制到其中。下面是一个以两种方式实现连接的包。如果您进行基准测试,您可以看到预分配速度快了约2倍,分配的内存也少得多 基准结果:
go test . -bench=. -benchmem
testing: warning: no tests to run
BenchmarkConcatCopyPreAllocate-8 30000000 47.9 ns/op 64 B/op 1 allocs/op
BenchmarkConcatAppend-8 20000000 107 ns/op 112 B/op 3 allocs/op
包壳:
package concat
func concatCopyPreAllocate(slices [][]byte) []byte {
var totalLen int
for _, s := range slices {
totalLen += len(s)
}
tmp := make([]byte, totalLen)
var i int
for _, s := range slices {
i += copy(tmp[i:], s)
}
return tmp
}
func concatAppend(slices [][]byte) []byte {
var tmp []byte
for _, s := range slices {
tmp = append(tmp, s...)
}
return tmp
}
基准测试:
package concat
import "testing"
var slices = [][]byte{
[]byte("my first slice"),
[]byte("second slice"),
[]byte("third slice"),
[]byte("fourth slice"),
[]byte("fifth slice"),
}
var B []byte
func BenchmarkConcatCopyPreAllocate(b *testing.B) {
for n := 0; n < b.N; n++ {
B = concatCopyPreAllocate(slices)
}
}
func BenchmarkConcatAppend(b *testing.B) {
for n := 0; n < b.N; n++ {
B = concatAppend(slices)
}
}
package concat
导入“测试”
变量片=[]字节{
[]字节(“我的第一个片”),
[]字节(“第二片”),
[]字节(“第三片”),
[]字节(“第四片”),
[]字节(“第五片”),
}
变量B[]字节
func BenchmarkConcatCopyPreAllocate(b*testing.b){
对于n:=0;n
似乎也支持这一更有效的解决方案。