英文:
Converting types for sorting : any runtime cost?
问题
我刚刚开始学习Go语言(两天前开始,写了不到1000行代码),对一些习惯用法还有些疑惑。
我需要按照字符串长度降序对一个字符串切片进行排序。我是这样做的:
首先,我想知道这是否是最常用的做法。
其次,我想知道当我写stringsLongestFirst(severalThousandStrings)
时,在底层会发生什么。字符串切片是否会被智能地重新解释为stringsLongestFirst
类型,还是我需要考虑一些复制开销?
(编辑:删除了与本例不相关的规范摘录)
英文:
I'm just getting to grips with Go (started two days ago and wrote less than 1000 lines), and I'm still wondering about some idioms.
I needed to sort a slice of strings by descending length. I did like so :
func ... {
... do business ...
sort.Sort(stringsLongestFirst(severalThousandStrings))
... carry on and be happy, because it works ...
}
type stringsLongestFirst []string
func (b stringsLongestFirst) Len() int { return len(b) }
func (b stringsLongestFirst) Less(i, j int) bool { return len(b[i]) > len(b[j]) }
func (b stringsLongestFirst) Swap(i, j int) { b[j], b[i] = b[i], b[j] }
First of all I wonder if this is the most idiomatic way to do it.
And then, most of all, I wonder about what happens under the hood when I write stringsLongestFirst(severalThousandStrings)
. Does the string slice somehow get smartly reinterpreted as a stringsLongestFirst
type, or do I have to count with some copying overhead ?
(edited : removed the excerpt from the specification, that was ill-suited to the case at hand)
答案1
得分: 3
你要翻译的内容如下:
你正在转换的类型既不是数字类型也不是字符串类型:[]string
和stringsLongestFirst
都是切片类型。
因此,转换应该不会产生比复制切片头部更多的开销(切片头部的大小为12或24个字节,取决于字长),这在将其作为interface{}
变量打包以调用Sort
时会发生。支持的数组没有被复制,这就是为什么在调用之后severalThousandStrings
看起来是排序的原因。
英文:
The types you are converting is neither a numeric type or a string: []string
and stringsLongestFirst
are slice types.
So the conversion should incur no more overhead than copying the slice header (which is 12 or 24 bytes, depending on the word size), which would happen anyway when packing it as an interface{}
variable in order to call Sort
. The backing array is not copied, which is why severalThousandStrings
appears to be sorted after the call.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论