Skip to content

Instantly share code, notes, and snippets.

@maxcal
Created May 5, 2020 20:56
Show Gist options
  • Save maxcal/87d022d183f87513a7669b1fda3d0911 to your computer and use it in GitHub Desktop.
Save maxcal/87d022d183f87513a7669b1fda3d0911 to your computer and use it in GitHub Desktop.
The great TR vs GSUB battle
require 'benchmark'
def vowel_cipher(string)
string.tr "aAeEiIoOuU", "eEiIoOuUaA"
end
NEXT_VOWEL = {"a"=>"e", "A"=>"E", "e"=>"i", "E"=>"I", "i"=>"o",
"I"=>"O", "o"=>"u", "O"=>"U", "u"=>"a", "U"=>"A"}
def vowel_cipher_gsub(str)
str.gsub(/[aeiou]/i, NEXT_VOWEL)
end
Benchmark.bm do |x|
x.report { 1000000.times { vowel_cipher("Paper Cup") } }
x.report { 1000000.times { vowel_cipher_gsub("Paper Cup") } }
end
user system total real
2.871711 0.000000 2.871711 ( 3.027596)
5.298556 0.000000 5.298556 ( 5.449371)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment