Skip to content

Commit

Permalink
Use strings.Builder to improve ChooseWords perf by 11% more
Browse files Browse the repository at this point in the history
  • Loading branch information
Jacalz committed May 29, 2024
1 parent a48f34f commit b7ccbac
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions wordlist/wordlist.go
Original file line number Diff line number Diff line change
Expand Up @@ -529,7 +529,8 @@ var Odd = [length]string{

// ChooseWords creates a list of words from the wordlist.
func ChooseWords(count uint) string {
words := make([]string, count)
words := strings.Builder{}
words.Grow(int(count) * 9)

buf := make([]byte, count)
_, err := rand.Read(buf)
Expand All @@ -538,12 +539,17 @@ func ChooseWords(count uint) string {
}

for i, wordIndex := range buf {
word := Even[wordIndex]
if i%2 == 0 {
words[i] = Odd[wordIndex]
} else {
words[i] = Even[wordIndex]
word = Odd[wordIndex]
}

words.WriteString(word)

if i != len(buf)-1 {
words.WriteByte('-')
}
}

return strings.Join(words, "-")
return words.String()
}

0 comments on commit b7ccbac

Please sign in to comment.