如何将一种数字类型的切片转换为另一种类型 [英] How to convert a slice of one numeric type to another type

查看:66
本文介绍了如何将一种数字类型的切片转换为另一种类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试Go语言,并且对它很陌生.我已经成功地完成了这些教程,现在正在编写一个小程序来评估其通常执行的操作类型的性能.我有一个很长的float32类型切片,需要将其尽可能有效地转换为float64类型的切片.除了遍历切片的元素并通过output [i] = float64(data [i])显式转换单个元素的类型之外,还有没有一种方法可以用来转换整个切片而无需迭代?我尝试寻找解决方案,但没有发现任何直接相关的内容.

I'm experimenting with the Go language and am quite new to it. I have successfully gone through the tutorials and am now writing a little program to evaluate its performance for the type of operations that I typically do. I have a lengthy slice of float32 type and need to convert it to a slice of type float64 as efficiently as possible. Other than iterating through the elements of the slice and explicitly converting types of individual elements via output[i] = float64(data[i]), is there method that I can use to convert the entire slice without need for iteration? I've tried searching for a solution but have not found anything directly related.

推荐答案

Go是相当底层的,这意味着遍历切片 是最有效的方法.其他语言可能具有用于此类事情的内置函数,但是它们所做的只是遍历切片,没有迭代就无法做到.但是有一些技巧,特别是使用范围,并避免对切片进行索引,因为越界检查会产生开销.这将是最有效的:

Go is quite low-level, this means that iterating through the slice is the most efficient method. Other languages may have built-in functions for such things, but all they do is iterate through the slice, there is no way to do it without the iteration. But there are some tricks, specifically use range and avoid indexing the slice as there is overhead in the out of bounds check. This would be the most efficient:

func convertTo64(ar []float32) []float64 {
   newar := make([]float64, len(ar))
   var v float32
   var i int
   for i, v = range ar {
      newar[i] = float64(v)
   }
   return newar
}

slice32 := make([]float32, 1000)
slice64 := convertTo64(slice32)

请注意,在范围循环中使用:=效率不高,因为在当前版本的Go中,变量每次都被丢弃并重新创建,而不是被重用.使用range代替for i=0; i<n; i++效率更高,因为它可以节省ar上的边界检查.

Note that the use of := in the range loop would be inefficient because in the current version of Go the variable is thrown away and recreated each time instead of being reused. Using range instead of for i=0; i<n; i++ is more efficient because it saves bounds checks on ar.

这篇关于如何将一种数字类型的切片转换为另一种类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆