Skip to content

Instantly share code, notes, and snippets.

@carpodaster
Created December 1, 2016 13:40
Show Gist options
  • Save carpodaster/24ddfa69ee5e4678fa87bc0f0d92bf79 to your computer and use it in GitHub Desktop.
Save carpodaster/24ddfa69ee5e4678fa87bc0f0d92bf79 to your computer and use it in GitHub Desktop.
Benchmarking German non-ascii downcase
require 'benchmark'
string = "HELLO WÖRLD WHÜTS ÄP?"
n = 500_000
# Using String#tr in one fell swoop
tr_single = ->(n, str) { n.times { str.tr('A-ZÄÜÖ', 'a-zäüö') } }
# Chaining outputs of String#tr
tr_multi = ->(n, str) { n.times { str.tr('A-Z', 'a-z').gsub('Ä','ä').gsub('Ü','ü').gsub('Ö','ö') } }
# Chaining outputs of String#gsub
gsub_mult = ->(n, str) { n.times { string.gsub('A-Z', 'a-z').gsub("Ä", "ä").gsub("Ö", "ö").gsub("Ü", "ü") } }
# Replacing umlauts with String#gsub and a dictionary
gsub_dict = ->(n, str) { n.times { string.gsub(/./, { 'A-Z' => 'a-z', "Ä" => "ä", "Ö" => "ö", "Ü" => "ü" }) }}
Benchmark.bm do |x|
x.report("tr single") { tr_single.(n, string) }
x.report("tr multi ") { tr_multi.(n, string) }
x.report("gsub mult") { gsub_mult.(n, string) }
x.report("gsub dict") { gsub_dict.(n, string) }
# "Native" multi-byte downcase in Ruby 2.4.0
if RUBY_VERSION >= "2.4.0"
x.report("2.4.0-p2 ") { n.times { string.downcase } }
end
end
__END__
user system total real
tr single 0.620000 0.000000 0.620000 ( 0.623868)
tr multi 1.810000 0.000000 1.810000 ( 1.811446)
gsub mult 1.480000 0.000000 1.480000 ( 1.481116)
gsub dict 4.320000 0.000000 4.320000 ( 4.324333)
@carpodaster
Copy link
Author

$ ruby -v 
ruby 2.4.0preview2 (2016-09-09 trunk 56129) [x86_64-linux]

$ ruby downcase_bench.rb 
       user     system      total        real
tr single  0.590000   0.000000   0.590000 (  0.594069)
tr multi   1.730000   0.000000   1.730000 (  1.737839)
gsub mult  1.390000   0.000000   1.390000 (  1.388327)
gsub dict  3.990000   0.000000   3.990000 (  3.991215)
2.4.0-p2   0.270000   0.000000   0.270000 (  0.268199)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment