[SOLVED] Fastest way to create string of the same character in Go

Issue

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)
}

Solution

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.

Answered By – VonC

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *