Testing ruby code with benchmark_suite

Just a couple days ago I found out therubygame.com which challenge us to solve a problem with ruby. The result were measured by the fastest, slowest, shortest, longest, cheaters (yup there are also some rule).

And also I was listening to an episode of ruby rouge on Benchmarking. And there is one tools called benchmark_suite.

So there is this challenge to capitalize first letter of every word. I want to compare my code to the fastest solution there. so i installed the gem, also the ruby-ffi gem that somewhat fix an error while I tried to run the benchmark.

so this is the code to benchmark it

 1  require 'benchmark/ips'
 2
 3  string = "The small brown & ginger fox JUMPED OVER the gate"
 4
 5  Benchmark.ips do |x|
 6    x.report("first") do
 7      string.gsub(/\w+/){|w| w.capitalize}
 8    end
 9
10    x.report("second") do
11      string.split.map(&:capitalize).join ' '
12    end
13  end

And here are the result

first 55609.3 (±10.7%) i/s - 277202 in 5.048175s (cycle=4471)

second 77996.4 (±10.2%) i/s - 389844 in 5.055319s (cycle=6188)

The first code run 55.609,3 times per second and the latter is 77.996,4 times per second. So the second code run more than the first code in one second. Which mean the second code is faster.

Also the first code run 277.202 times in 5.048175 sec while the second code run 389.844 times in 5.05 sec

So this mean, that regex is more slower then calling capitalized on each element on array