ruby-i18n / i18n

Internationalization (i18n) library for Ruby
MIT License
976 stars 408 forks source link

Optimize `I18n.t` #651

Closed fatkodima closed 1 year ago

fatkodima commented 1 year ago

Benchmarks

# frozen_string_literal: true

require "bundler/inline"

gemfile(true) do
  source "https://rubygems.org"

  git_source(:github) { |repo| "https://github.com/#{repo}.git" }

  gem "benchmark-ips"
  gem "i18n", path: "~/Desktop/oss/i18n"
end

require "i18n"

I18n.backend = I18n::Backend::Simple.new
I18n.backend.store_translations(:en, :foo => 'Foo in :en', :bar => 'Bar in :en', :buz => 'Buz in :en', :interpolate => 'Interpolate %{value}', :interpolate_count => 'Interpolate %{value} %{count}')

puts "Key exists\n"
Benchmark.ips do |x|
  x.report("original") do
    I18n.translate(:foo, locale: :en)
  end

  x.report("optimized") do
    I18n.translate_optimized(:foo, locale: :en)
  end

  x.compare!
end

puts "\nMissing key and default\n"
Benchmark.ips do |x|
  x.report("original") do
    I18n.translate(:missing, default: "foo")
  end

  x.report("optimized") do
    I18n.translate_optimized(:missing, default: "foo")
  end

  x.compare!
end

puts "\nInterpolation\n"
Benchmark.ips do |x|
  x.report("original") do
    I18n.translate(:interpolate, value: "foo")
  end

  x.report("optimized") do
    I18n.translate_optimized(:interpolate, value: "foo")
  end

  x.compare!
end

Results

Warming up --------------------------------------
            original    18.193k i/100ms
           optimized    22.853k i/100ms
Calculating -------------------------------------
            original    182.271k (± 1.8%) i/s -    927.843k in   5.092162s
           optimized    235.982k (± 1.8%) i/s -      1.188M in   5.037393s

Comparison:
           optimized:   235982.5 i/s
            original:   182271.0 i/s - 1.29x  slower

Missing key and default
Warming up --------------------------------------
            original    14.985k i/100ms
           optimized    16.688k i/100ms
Calculating -------------------------------------
            original    148.773k (± 1.5%) i/s -    749.250k in   5.037379s
           optimized    166.369k (± 1.8%) i/s -    834.400k in   5.017022s

Comparison:
           optimized:   166368.8 i/s
            original:   148773.1 i/s - 1.12x  slower

Interpolation
Warming up --------------------------------------
            original     2.240k i/100ms
           optimized     8.674k i/100ms
Calculating -------------------------------------
            original     22.684k (± 3.6%) i/s -    114.240k in   5.042754s
           optimized     87.651k (± 2.5%) i/s -    442.374k in   5.050116s

Comparison:
           optimized:    87651.2 i/s
            original:    22684.0 i/s - 3.86x  slower
radar commented 1 year ago

Thank you! These changes look great to me, I’ll merge them in next time I’m doing my OSS merging routine, likely this coming Monday or the Monday after.