Skip to content

Commit f431b61

Browse files
committed
Avoid needless word-list copies in Lorem.words
Only concatenate the supplemental list when requested, and only duplicate the word list when more words are asked for than the list contains. The list returned by translate is never mutated, since it may be the array cached by the I18n backend. Benchmark (Ruby 3.4.9, arm64-darwin25, benchmark-ips): require 'benchmark/ips' require 'faker' Benchmark.ips do |x| x.config(warmup: 2, time: 5) x.report('words(number: 4)') { Faker::Lorem.words(number: 4) } x.report('sentence') { Faker::Lorem.sentence } x.report('paragraph') { Faker::Lorem.paragraph } end Results: main: words(number: 4) 126.489k (+/- 2.2%) i/s sentence 40.797k (+/- 4.4%) i/s paragraph 12.455k (+/- 0.7%) i/s this commit: words(number: 4) 132.863k (+/- 1.0%) i/s (~1.05x) sentence 43.273k (+/- 0.4%) i/s (~1.06x) paragraph 12.733k (+/- 1.4%) i/s (~1.02x)
1 parent 9b07803 commit f431b61

1 file changed

Lines changed: 6 additions & 5 deletions

File tree

lib/faker/default/lorem.rb

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,15 +36,16 @@ def word(exclude_words: nil)
3636
# @faker.version 2.1.3
3737
def words(number: 3, supplemental: false, exclude_words: nil)
3838
resolved_num = resolve(number)
39-
word_list = (
40-
translate('faker.lorem.words') +
41-
(supplemental ? translate('faker.lorem.supplemental') : [])
42-
)
39+
word_list = translate('faker.lorem.words')
40+
word_list += translate('faker.lorem.supplemental') if supplemental
4341
if exclude_words
4442
exclude_words = exclude_words.split(', ') if exclude_words.instance_of?(::String)
4543
word_list -= exclude_words
4644
end
47-
word_list *= ((resolved_num / word_list.length) + 1)
45+
# Duplicate the word list only when more words are requested than the
46+
# list contains. Never mutate word_list itself: it may be the array
47+
# cached by the I18n backend.
48+
word_list *= ((resolved_num / word_list.length) + 1) if resolved_num > word_list.length
4849
sample(word_list, resolved_num)
4950
end
5051

0 commit comments

Comments
 (0)