Developers usually feel that ruby is a slow language in terms of time efficiency. This is true but if you use some tricks, your ruby code can run faster. I am giving you some tips (with example) to optimize your ruby code and you can see the results in practice.
How to profile: To know, where to make changes in your code to run faster, you need to profile your code. You can use inbuild “benchmark” library or Ruby-Prof for this purpose. Though there are many other tools, but I found these 2 very suitable and easy to use. Ruby-Prof gives you output in multiple formats so that you can analyze it easily.
Tip #1 :- Printing
Consider following ruby code, how can we make it fast?
require 'benchmark'
n = 50_000
for i in 1..n do
$stderr.print i, "and"
$stderr.puts i
end
Above code has a couple of problems, which are making in run slow:
- We are using 2 distinct functions calls (puts and print).
- We are using ‘puts’, which includes the overhead of adding a ‘\n’ to every line that doesn't already have one.
require 'benchmark'
n = 50_000
Benchmark.bmbm(15) do |r|
r.report("original version 2 calls") do
for i in 1..n do
$stderr.print i, "and"
$stderr.puts i
end
end
r.report("single puts call") do
for i in 1..n do
$stderr.puts "#{i} and #{i}"
end
end
r.report("single print call") do
for i in 1..n do
$stderr.print "#{i} and #{i}\n"
end
end
end
When I run this script, I found following results from benchmarking:
Above results clearly show an improvement of reducing function calls and of using 'print' over 'puts'.akash$ ruby puts_print.rb 2> /dev/null
Rehearsal ------------------------------------------------------------
original version 2 calls 0.370000 0.260000 0.630000 ( 0.639098)
single puts call 0.250000 0.140000 0.390000 ( 0.397769)
single print call 0.170000 0.070000 0.240000 ( 0.256804)
--------------------------------------------------- total: 1.260000sec
user system total real
original version 2 calls 0.380000 0.270000 0.650000 ( 0.658632)
single puts call 0.240000 0.140000 0.380000 ( 0.390004)
single print call 0.170000 0.070000 0.240000 ( 0.250661)
Subscribe - To get an automatic feed of all future posts subscribe here, or to receive them via email go here and enter your email address in the box. You can also like us on facebook and follow me on Twitter @akashag1001.
This post is very beautiful and well-maintained, and it deserves to be recognised. Thank you for your time and effort, and please continue to update.Web Design Company USA
I adore your work, and it greatly motivates me.
Software Testing Services
This is just what I was looking for. Thank you for sharing this essential information. It is quite beneficial.
QA Testing Services