转换类型以进行排序:是否有任何运行时成本?

huangapple go评论113阅读模式
英文:

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 :

  1. func ... {
  2. ... do business ...
  3. sort.Sort(stringsLongestFirst(severalThousandStrings))
  4. ... carry on and be happy, because it works ...
  5. }
  6. type stringsLongestFirst []string
  7. func (b stringsLongestFirst) Len() int { return len(b) }
  8. func (b stringsLongestFirst) Less(i, j int) bool { return len(b[i]) > len(b[j]) }
  9. 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

你要翻译的内容如下:

你正在转换的类型既不是数字类型也不是字符串类型:[]stringstringsLongestFirst都是切片类型。

因此,转换应该不会产生比复制切片头部更多的开销(切片头部的大小为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.

huangapple
  • 本文由 发表于 2015年8月3日 05:05:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/31776584.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定