加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 09:22:03 所属栏目:大数据 来源:网络整理
导读:我完全理解Go不提供对泛型的支持,而是选择用户在需要时创建自己的特定于类型的方法. 但是,我想知道是否有更有效的方法在数据结构上创建一个特定的map函数,该数据结构不涉及遍历整个列表并应用该函数,或者这是其他语言支持泛型的幕后操作. 例: func map(list
我完全理解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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读