Skip to content

Instantly share code, notes, and snippets.

@awesome
Created July 2, 2016 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save awesome/6a2693f7dc7f917944ea1b08697149f2 to your computer and use it in GitHub Desktop.
Save awesome/6a2693f7dc7f917944ea1b08697149f2 to your computer and use it in GitHub Desktop.
# "[A]pplying downcase once is better than calling it (possibly) multiple times?"--sawa
# via http://stackoverflow.com/questions/38162768/38163148#comment63754959_38163167
# "How to make a string 1st letter caps, 2nd letter noncaps, 3rd letter caps, 4th letter noncaps…?"
require "benchmark"
n = 1_000_000
Benchmark.bmbm do |x|
x.report("String#downcase.chars.map.with_index {|c,i| i%2==0 ? c.upcase : c}.join") do
n.times {
"Stackoverflow is awesome!".downcase.chars.map.with_index {|c,i| i%2==0 ? c.upcase : c}.join
}
end
x.report("String#chars.map.with_index {|c,i| i%2==0 ? c.upcase : c.downcase}.join") do
n.times {
"Stackoverflow is awesome!".chars.map.with_index {|c,i| i%2==0 ? c.upcase : c.downcase}.join
}
end
end
# $ ruby benchmark_downcase_vs_enum_downcase.rb
# Rehearsal -----------------------------------------------------------------------------------------------------------
# String#downcase.chars.map.with_index {|c,i| i%2==0 ? c.upcase : c}.join 10.750000 0.030000 10.780000 ( 10.801773)
# String#chars.map.with_index {|c,i| i%2==0 ? c.upcase : c.downcase}.join 11.580000 0.020000 11.600000 ( 11.635031)
# ------------------------------------------------------------------------------------------------- total: 22.380000sec
#
# user system total real
# String#downcase.chars.map.with_index {|c,i| i%2==0 ? c.upcase : c}.join 10.570000 0.030000 10.600000 ( 10.621634)
# String#chars.map.with_index {|c,i| i%2==0 ? c.upcase : c.downcase}.join 12.210000 0.070000 12.280000 ( 12.588328)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment