8 Go Techniques for Fast Random Alphabetic Strings – Benchmarks & Insights

This article compares eight Go implementations for generating random strings of English letters, explains their trade‑offs, presents detailed benchmark results, and shows how using byte slices, masking, rand.Source, strings.Builder, and unsafe can dramatically improve speed and memory usage.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
8 Go Techniques for Fast Random Alphabetic Strings – Benchmarks & Insights

Preface

Question: In Go, what is the fastest and simplest way to generate a random string that contains only English letters?

1. Runes

A straightforward solution that declares a rune slice and picks random runes.

package approach1

import (
    "fmt"
    "math/rand"
    "testing"
    "time"
)

var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

func randStr(n int) string {
    b := make([]rune, n)
    for i := range b {
        b[i] = letters[rand.Intn(len(letters))]
    }
    return string(b)
}

func TestApproach1(t *testing.T) {
    rand.Seed(time.Now().UnixNano())
    fmt.Println(randStr(10))
}

func BenchmarkApproach1(b *testing.B) {
    rand.Seed(time.Now().UnixNano())
    for i := 0; i < b.N; i++ {
        _ = randStr(10)
    }
}

2. Bytes

Since English letters map one‑to‑one with bytes in UTF‑8, we can store the alphabet as a byte slice or constant.

const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
package approach2

import (
    "fmt"
    "math/rand"
    "testing"
    "time"
)

const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

func randStr(n int) string {
    b := make([]byte, n)
    for i := range b {
        b[i] = letters[rand.Intn(len(letters))]
    }
    return string(b)
}

func TestApproach2(t *testing.T) {
    rand.Seed(time.Now().UnixNano())
    fmt.Println(randStr(10))
}

func BenchmarkApproach2(b *testing.B) {
    rand.Seed(time.Now().UnixNano())
    for i := 0; i < b.N; i++ {
        _ = randStr(10)
    }
}

3. Remainder

Use rand.Int63() and take the remainder modulo the alphabet length, which is faster than rand.Intn().

package approach3

import (
    "fmt"
    "math/rand"
    "testing"
    "time"
)

const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

func randStr(n int) string {
    b := make([]byte, n)
    for i := range b {
        b[i] = letters[rand.Int63()%int64(len(letters))]
    }
    return string(b)
}

func TestApproach3(t *testing.T) {
    rand.Seed(time.Now().UnixNano())
    fmt.Println(randStr(10))
}

func BenchmarkApproach3(b *testing.B) {
    rand.Seed(time.Now().UnixNano())
    for i := 0; i < b.N; i++ {
        _ = randStr(10)
    }
}

4. Masking

Generate 63 random bits with rand.Int63() and mask the lower 6 bits (enough for 52 letters). Discard values ≥ len(letters).

package approach4

import (
    "fmt"
    "math/rand"
    "testing"
    "time"
)

const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

const (
    letterIdBits = 6                     // 6 bits to represent a letter index
    letterIdMask = 1<<letterIdBits - 1   // All 1‑bits for the mask
)

func randStr(n int) string {
    b := make([]byte, n)
    for i := range b {
        if idx := int(rand.Int63() & letterIdMask); idx < len(letters) {
            b[i] = letters[idx]
        } else {
            i-- // retry this position
        }
    }
    return string(b)
}

func TestApproach4(t *testing.T) {
    rand.Seed(time.Now().UnixNano())
    fmt.Println(randStr(10))
}

func BenchmarkApproach4(b *testing.B) {
    rand.Seed(time.Now().UnixNano())
    for i := 0; i < b.N; i++ {
        _ = randStr(10)
    }
}

5. Masking Improved

Cache the result of rand.Int63() and extract up to ten letters from the 63 bits, reducing the number of calls.

package approach5

import (
    "fmt"
    "math/rand"
    "testing"
    "time"
)

const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

const (
    letterIdBits = 6
    letterIdMask = 1<<letterIdBits - 1
    letterIdMax  = 63 / letterIdBits // how many letters per Int63
)

func randStr(n int) string {
    b := make([]byte, n)
    for i, cache, remain := n-1, rand.Int63(), letterIdMax; i >= 0; {
        if remain == 0 {
            cache, remain = rand.Int63(), letterIdMax
        }
        if idx := int(cache & letterIdMask); idx < len(letters) {
            b[i] = letters[idx]
            i--
        }
        cache >>= letterIdBits
        remain--
    }
    return string(b)
}

func TestApproach5(t *testing.T) {
    rand.Seed(time.Now().UnixNano())
    fmt.Println(randStr(10))
}

func BenchmarkApproach5(b *testing.B) {
    rand.Seed(time.Now().UnixNano())
    for i := 0; i < b.N; i++ {
        _ = randStr(10)
    }
}

6. Using rand.Source

Replace the default rand.Rand with a dedicated rand.Source for better performance in single‑goroutine scenarios.

package approach6

import (
    "fmt"
    "math/rand"
    "testing"
    "time"
)

const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

var src = rand.NewSource(time.Now().UnixNano())

const (
    letterIdBits = 6
    letterIdMask = 1<<letterIdBits - 1
    letterIdMax  = 63 / letterIdBits
)

func randStr(n int) string {
    b := make([]byte, n)
    for i, cache, remain := n-1, src.Int63(), letterIdMax; i >= 0; {
        if remain == 0 {
            cache, remain = src.Int63(), letterIdMax
        }
        if idx := int(cache & letterIdMask); idx < len(letters) {
            b[i] = letters[idx]
            i--
        }
        cache >>= letterIdBits
        remain--
    }
    return string(b)
}

func TestApproach6(t *testing.T) {
    fmt.Println(randStr(10))
}

func BenchmarkApproach6(b *testing.B) {
    for i := 0; i < b.N; i++ {
        _ = randStr(10)
    }
}

7. Using strings.Builder

Build the result with strings.Builder, pre‑allocating the required capacity to avoid extra allocations.

package approach7

import (
    "fmt"
    "math/rand"
    "strings"
    "testing"
    "time"
)

const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

var src = rand.NewSource(time.Now().UnixNano())

const (
    letterIdBits = 6
    letterIdMask = 1<<letterIdBits - 1
    letterIdMax  = 63 / letterIdBits
)

func randStr(n int) string {
    var sb strings.Builder
    sb.Grow(n)
    for i, cache, remain := n-1, src.Int63(), letterIdMax; i >= 0; {
        if remain == 0 {
            cache, remain = src.Int63(), letterIdMax
        }
        if idx := int(cache & letterIdMask); idx < len(letters) {
            sb.WriteByte(letters[idx])
            i--
        }
        cache >>= letterIdBits
        remain--
    }
    return sb.String()
}

func TestApproach7(t *testing.T) {
    fmt.Println(randStr(10))
}

func BenchmarkApproach7(b *testing.B) {
    for i := 0; i < b.N; i++ {
        _ = randStr(10)
    }
}

8. Mimicking strings.Builder with unsafe

Convert the underlying byte slice directly to a string using the unsafe package, eliminating the final copy.

package approach8

import (
    "fmt"
    "math/rand"
    "testing"
    "time"
    "unsafe"
)

const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

var src = rand.NewSource(time.Now().UnixNano())

const (
    letterIdBits = 6
    letterIdMask = 1<<letterIdBits - 1
    letterIdMax  = 63 / letterIdBits
)

func randStr(n int) string {
    b := make([]byte, n)
    for i, cache, remain := n-1, src.Int63(), letterIdMax; i >= 0; {
        if remain == 0 {
            cache, remain = src.Int63(), letterIdMax
        }
        if idx := int(cache & letterIdMask); idx < len(letters) {
            b[i] = letters[idx]
            i--
        }
        cache >>= letterIdBits
        remain--
    }
    return *(*string)(unsafe.Pointer(&b))
}

func TestApproach8(t *testing.T) {
    fmt.Println(randStr(10))
}

func BenchmarkApproach8(b *testing.B) {
    for i := 0; i < b.N; i++ {
        _ = randStr(10)
    }
}

Benchmark

Running go test ./... -bench=. -benchmem yields the following results (original author):

BenchmarkRunes-4                     2000000    723 ns/op   96 B/op   2 allocs/op
BenchmarkBytes-4                     3000000    550 ns/op   32 B/op   2 allocs/op
BenchmarkBytesRmndr-4                3000000    438 ns/op   32 B/op   2 allocs/op
BenchmarkBytesMask-4                 3000000    534 ns/op   32 B/op   2 allocs/op
BenchmarkBytesMaskImpr-4            10000000    176 ns/op   32 B/op   2 allocs/op
BenchmarkBytesMaskImprSrc-4         10000000    139 ns/op   32 B/op   2 allocs/op
BenchmarkBytesMaskImprSrcSB-4       10000000    134 ns/op   16 B/op   1 allocs/op
BenchmarkBytesMaskImprSrcUnsafe-4   10000000    115 ns/op   16 B/op   1 allocs/op

Re‑tested by the translator:

BenchmarkApproach1-12            3849038               299.5 ns/op            64 B/op          2 allocs/op
BenchmarkApproach2-12            5545350               216.4 ns/op            32 B/op          2 allocs/op
BenchmarkApproach3-12            7003654               169.7 ns/op            32 B/op          2 allocs/op
BenchmarkApproach4-12            7164259               168.7 ns/op            32 B/op          2 allocs/op
BenchmarkApproach5-12           13205474                89.06 ns/op           32 B/op          2 allocs/op
BenchmarkApproach6-12           13665636                84.41 ns/op           32 B/op          2 allocs/op
BenchmarkApproach7-12           17213431                70.37 ns/op           16 B/op          1 allocs/op
BenchmarkApproach8-12           19756956                61.41 ns/op           16 B/op          1 allocs/op

Key observations:

Switching from rune to byte improves performance by over 20%.

Using rand.Int63() instead of rand.Intn() yields another >20% gain.

Masking alone does not speed up the code; in some cases it slows it down.

Caching the 63 random bits and extracting multiple letters gives a 3× speed boost.

Replacing rand.Rand with rand.Source improves performance by about 21%.

Employing strings.Builder reduces allocations and adds roughly 3.5% speed improvement.

Using unsafe to convert the byte slice to a string cuts the runtime by another ~14%.

Overall, Approach 8 is about 6.3× faster than Approach 1, uses only one‑sixth of the memory, and halves the allocation count.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendperformanceBenchmarkrandom-string
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.