Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Performance: Cache translations to reduce file read and parse operations #2939

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion lib/faker.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,13 @@ def random
end
end

# rubocop:disable Style/ClassVars
class Base
Numbers = Array(0..9)
ULetters = Array('A'..'Z')
LLetters = Array('a'..'z')
Letters = ULetters + LLetters
@@translate_cache = {}
alextaujenis marked this conversation as resolved.
Show resolved Hide resolved

class << self
attr_reader :flexible_key
Expand Down Expand Up @@ -161,8 +163,9 @@ def parse(key)
# locale is specified
def translate(*args, **opts)
opts[:locale] ||= Faker::Config.locale
translate_key = args.to_s + opts.sort.join
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe translate_key should be hashed?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It does sound reasonable to hash the translate_key, but there is no reason to compute this digest because the translate_key (as provided in this PR) is a valid string and can be used for lookups. The extra time taken on every method call to compute even an md5 digest erases all performance gains for this PR.

Another interesting fact here is that i18n computes the sha256 digest for all cache keys if you enable their default translation cache. This suggests that implementing the i18n default cache will also erase the performance gains for this PR.

opts[:raise] = true
I18n.translate(*args, **opts)
@@translate_cache[translate_key] ||= I18n.translate(*args, **opts)
rescue I18n::MissingTranslationData
opts[:locale] = :en

Expand Down Expand Up @@ -268,6 +271,7 @@ def disable_enforce_available_locales
end
end
end
# rubocop:enable Style/ClassVars
end

# require faker objects
Expand Down
Loading