douhulao7642 2014-08-21 10:37
浏览 403
已采纳

在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 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥25 关于##爬虫##的问题,如何解决?:
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误