泛型 – Golang效率中的非通用映射

我完全理解Go不提供对泛型的支持,而是选择用户在需要时创建自己的特定于类型的方法.

但是,我想知道是否有更有效的方法在数据结构上创建一个特定的map函数,该数据结构不涉及遍历整个列表并应用该函数,或者这是其他语言支持泛型的幕后操作.

例:

func map(list []string,op func(string)string) []string {
  ouput := make([]string,len(list))
  for i,v := range list {
    output[i] = op(v)
  }
  return output
}

谢谢!

解决方法

仅供参考,地图是保留字,因此您无法使您的功能与使用小写地图完全一致.

这可能就像你能得到的一样好.泛型不会让你分配新的内存.

使用append()稍微快一些,而不是在开始时将整个切片初始化为空字符串.例如:

func Map(list []string,op func(string) string) []string {
   output := make([]string,len(list))
   for _,v := range list {
      output = append(output,op(v))
   }
   return output
}

这让我的速度增加了10%.

更新:这只适用于非常短的切片.这是一个更彻底的基准 – 在更长的切片上使用追加实际上更慢.我也试过并行化,这只是在更大的切片上的开销.

码:
https://gist.github.com/8250514

输出(测试名称末尾的数字是切片长度):

go test -bench=".*" -test.cpu=2
BenchmarkSliceMake10-2       5000000           473 ns/op
BenchmarkSliceMake100-2       500000          3637 ns/op
BenchmarkSliceMake1000-2       50000         43920 ns/op
BenchmarkSliceMake10000-2       5000        539743 ns/op
BenchmarkSliceAppend10-2     5000000           464 ns/op
BenchmarkSliceAppend100-2     500000          4303 ns/op
BenchmarkSliceAppend1000-2     50000         51172 ns/op
BenchmarkSliceAppend10000-2     5000        595650 ns/op
BenchmarkSlicePar10-2         500000          3784 ns/op
BenchmarkSlicePar100-2        200000          7940 ns/op
BenchmarkSlicePar1000-2        50000         50118 ns/op
BenchmarkSlicePar10000-2        5000        465540 ns/op

相关文章

类型转换 1、int转string 2、string转int 3、string转float ...
package main import s "strings" import...
类使用:实现一个people中有一个sayhi的方法调用功能,代码如...
html代码: beego代码:
1、读取文件信息: 2、读取文件夹下的所有文件: 3、写入文件...
配置环境:Windows7+推荐IDE:LiteIDEGO下载地址:http:...