Lets say we need to benchmark and evaluate the performance of code snippet.
This is how we can easily do on Rails console using "Benchmark.ms"
require 'benchmark'
1.9.3-p392 :001 > Benchmark.measure do
1.9.3-p392 :002 > "john mark McMillan".split(" ").collect{|word|word[0] = word[0].upcase; word}.join(" ")
1.9.3-p392 :003?> end
=> #<Benchmark::Tms:0x00007ff6cd8face8 @label="", @real=1.600012183189392e-05, @cstime=0.0, @cutime=0.0, @stime=2.9999999999960614e-06, @utime=1.8999999999991246e-05, @total=2.1999999999987307e-05
1.9.3-p392 :004 > Benchmark.ms do
1.9.3-p392 :005 > "john mark McMillan".gsub(/\b\w/) { |w| w.upcase }
1.9.3-p392 :006?> end
=> #<Benchmark::Tms:0x00007ff6cd91f688 @label="", @real=0.0009869998320937157, @cstime=0.0, @cutime=0.0, @stime=0.00010900000000000493, @utime=4.500000000001725e-05, @total=0.00015400000000002217>
The above values from Benchmark output clearly shows that "regex" operations are comparatively slower in execution than collect method.
Use Benchmark.measure
often on your code snippets to detect the performance and optimise accordingly.
Here is a ruby doc to learn more about Benchmarking.
Reference and Credits for code snippet: https://stackoverflow.com/questions/5615597/why-does-rails-titlecase-add-a-space-to-a-name/43135345