/ benchmarking

Benchmarking in Rails console - Know performance of a code snippet

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"

1.9.3-p392 :001 > Benchmark.ms 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
 => 0.015000000000000001 
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
 => 0.024 

The above values from Benchmark output clearly shows that "regex" operations are comparatively slower in execution than collect method.

Though, its a small performance gain over regex operation i.e. by 0.1 ms but its still a considerable gain by almost 100%. Thus a group of code snippet in a method or in a loop can gain significantly by replacing such slower performing operations.

Suggestion - Use Benchmarking.ms often on your code snippets to detect the performance and optimise accordingly.

Rohan Daxini

Rohan Daxini

Founder at Kiprosh | Ruby, Elixir, JS & C lover | Life Long Learner | Books | Technology | Mindfulness | Gratitude

Read More