Fastest way to create string of the same character in Go

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

Fastest way to create string of the same character in Go

问题

我想知道创建一个由相同字符的n个实例组成的字符串的最快方法是什么。我可以想象几种方法,有些天真,有些不太天真:

字符串拼接(非常天真)

  1. func nchars(b byte, n int) string {
  2. s := ""
  3. c := string([]byte{b})
  4. for i := 0; i < n; i++ {
  5. s += c
  6. }
  7. return s
  8. }

字节切片

  1. func nchars(b byte, n int) string {
  2. s := make([]byte, n)
  3. for i := 0; i < n; i++ {
  4. s[i] = b
  5. }
  6. return string(s)
  7. }
英文:

I'm wondering what the fastest way would be to create a string of n instances of the same character. I could imagine a few approaches, some naive and some less so:

String concatenation (very naive)

  1. func nchars(b byte, n int) string {
  2. s := &quot;&quot;
  3. c := string([]byte{b})
  4. for i := 0; i &lt; n; i++ {
  5. s += c
  6. }
  7. return s
  8. }

Byte slice

  1. func nchars(b byte, n int) string {
  2. s := make([]byte, n)
  3. for i := 0; i &lt; n; i++ {
  4. s[i] = b
  5. }
  6. return string(s)
  7. }

答案1

得分: 8

字节切片的方法至少在strings.Repeat中被选择:请参考它的源代码

  1. b := make([]byte, len(s)*count)
  2. bp := 0
  3. for i := 0; i < count; i++ {
  4. bp += copy(b[bp:], s)
  5. }
  6. return string(b)

所以我会选择你的第二个选择。

英文:

The byte slice approach is at least the one chosen in strings.Repeat: see its source:

  1. b := make([]byte, len(s)*count)
  2. bp := 0
  3. for i := 0; i &lt; count; i++ {
  4. bp += copy(b[bp:], s)
  5. }
  6. return string(b)

So I would go with your second choice.

答案2

得分: 4

res1 := strings.Repeat(str1, 4) 的中文翻译是:res1 := strings.Repeat(str1, 4)。

英文:
  1. res1 := strings.Repeat(str1, 4)

huangapple
  • 本文由 发表于 2014年8月21日 18:37:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/25424184.html
匿名

发表评论

匿名网友

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

确定