Skip to content

Commit ee54e80

Browse files
committed
perf: use instance of rand instead of global
Use an instance of rand for random number generation instead of using the global rand. Adjust seeding of rand.
1 parent 57d9730 commit ee54e80

File tree

2 files changed

+8
-14
lines changed

2 files changed

+8
-14
lines changed

generator.go

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import (
1212
type Generator struct {
1313
dict *Dictionary
1414
delimiter string
15-
seed int64
15+
rand *rand.Rand
1616
size uint
1717
}
1818

@@ -29,7 +29,7 @@ func WithDelimiter(delimiter string) GeneratorOption {
2929
// WithSeed sets the seed used to generate random numbers.
3030
func WithSeed(seed int64) GeneratorOption {
3131
return func(r *Generator) {
32-
r.seed = seed
32+
r.rand.Seed(seed)
3333
}
3434
}
3535

@@ -45,33 +45,32 @@ func NewGenerator(opts ...GeneratorOption) *Generator {
4545
r := &Generator{
4646
dict: NewDictionary(),
4747
delimiter: "-",
48-
seed: time.Now().UnixNano(),
48+
rand: rand.New(rand.NewSource(time.Now().UnixNano())),
4949
size: 2,
5050
}
5151
for _, opt := range opts {
5252
opt(r)
5353
}
54-
rand.Seed(r.seed)
5554
return r
5655
}
5756

5857
// Generate generates a random name.
5958
func (r *Generator) Generate() (string, error) {
6059
// TODO: address case where adjective and noun are the same, such as "orange-orange" or "sound-sound"
61-
adjective := r.dict.adectives[rand.Intn(r.dict.LengthAdjective())]
62-
noun := r.dict.nouns[rand.Intn(r.dict.LengthNoun())]
60+
adjective := r.dict.adectives[r.rand.Intn(r.dict.LengthAdjective())]
61+
noun := r.dict.nouns[r.rand.Intn(r.dict.LengthNoun())]
6362
words := []string{adjective, noun}
6463

6564
switch r.size {
6665
case 2:
6766
return strings.Join(words, r.delimiter), nil
6867
case 3:
69-
verb := r.dict.verbs[rand.Intn(r.dict.LengthVerb())]
68+
verb := r.dict.verbs[r.rand.Intn(r.dict.LengthVerb())]
7069
words = append(words, verb)
7170
case 4:
72-
verb := r.dict.verbs[rand.Intn(r.dict.LengthVerb())]
71+
verb := r.dict.verbs[r.rand.Intn(r.dict.LengthVerb())]
7372
words = append(words, verb)
74-
adverb := r.dict.adverbs[rand.Intn(r.dict.LengthAdverb())]
73+
adverb := r.dict.adverbs[r.rand.Intn(r.dict.LengthAdverb())]
7574
words = append(words, adverb)
7675
default:
7776
return "", fmt.Errorf("invalid size: %d", r.size)

generator_test.go

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -39,11 +39,6 @@ func TestNewGenerator(t *testing.T) {
3939
t.Fatal("\t\tShould be able to set the delimiter of the phrase.")
4040
}
4141
t.Log("\t\tShould be able to set the delimiter of the phrase.")
42-
43-
if g.seed != 12345 {
44-
t.Fatal("\t\tShould be able to set the seed of the phrase.")
45-
}
46-
t.Log("\t\tShould be able to set the seed of the phrase.")
4742
}
4843
}
4944
}

0 commit comments

Comments
 (0)