douhulao7642
2014-08-21 10:37 阅读 206
已采纳

在Go中创建相同字符的字符串的最快方法

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)

func nchars(b byte, n int) string {
    s := ""
    c := string([]byte{b})
    for i := 0; i < n; i++ {
        s += c
    }
    return s
}

Byte slice

func nchars(b byte, n int) string {
    s := make([]byte, n)
    for i := 0; i < n; i++ {
        s[i] = b
    }
    return string(s)
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    doucheng3407 doucheng3407 2014-08-21 10:45

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

    b := make([]byte, len(s)*count)
    bp := 0
    for i := 0; i < count; i++ {
            bp += copy(b[bp:], s)
    }
    return string(b)
    

    So I would go with your second choice.

    点赞 评论 复制链接分享

相关推荐