Skip to content

Commit 618bf38

Browse files
committed
Use memoized I18n.locale_available? in Config.locale
I18n.locale_available? checks a memoized set of locales, unlike I18n.available_locales which rebuilds its array on every call, so the common case (the current I18n locale is available) no longer allocates. Benchmark (Ruby 3.4.9, arm64-darwin25, benchmark-ips): require 'benchmark/ips' require 'faker' Benchmark.ips do |x| x.config(warmup: 1, time: 2) x.report('Config.locale') { Faker::Config.locale } end Results: main: Config.locale 178.877k (+/-16.1%) i/s this commit: Config.locale 992.950k (+/- 2.5%) i/s (~5.5x)
1 parent 9b07803 commit 618bf38

1 file changed

Lines changed: 4 additions & 1 deletion

File tree

lib/faker.rb

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,10 @@ def locale=(new_locale)
2424

2525
def locale
2626
# Because I18n.locale defaults to :en, if we don't have :en in our available_locales, errors will happen
27-
Thread.current[:faker_config_locale] || @default_locale || (I18n.available_locales.include?(I18n.locale) ? I18n.locale : I18n.available_locales.first)
27+
# I18n.locale_available? is used here because it relies on a memoized
28+
# set of locales, unlike I18n.available_locales which is recomputed
29+
# on every call.
30+
Thread.current[:faker_config_locale] || @default_locale || (I18n.locale_available?(I18n.locale) ? I18n.locale : I18n.available_locales.first)
2831
end
2932

3033
def own_locale

0 commit comments

Comments
 (0)