Benchmarking Ruby Control Flows and Datastructures
Flexibility of Ruby brings many ways to achieve the same results, whether it is a loop, selection of elements from datastructures, or assignment of values.
Performance is one of the major metrics of an application. Ruby provides a module, natively brought by the language, called Benchmark, which helps us to observe the code and reflects the potential bottlenecks.
Sometimes that is very suprising which statement executes faster and which of them provides less performance. In this post I present some results of benchmarked codes, operators, searching, hash, array manipulations, which I consider suprising or unexpected.
Which one is faster?
- Object nil check:
unless objthough.nil?is nicer and readable - For looping:
whileoruntil - Array creation:
[]is unbeatable - Array with values:
(...).to_ais the fastest - Array emptyness check:
.empty?is much faster thanarr == [] - For extending an array:
+is faster thanconcat - Iterate over a sorted array and compare its elements is faster than the same with an unsorted array
{}is faster thannew- In case of
Hashuse.empty?to check emptyness, and readable as well - For adding new element
[]andstoreare almost the same,mergeis far slowest - Iterate over a
Hash, get the keys first by.keysfaster thaneach,each_keysoreach_pair - For selecting elements, use
keep_ifordelete_if, they are almost on the same performance.selectis slow - Check whether a key exists, use
[]..has_key?is far slower - Empty string assign is the faster string initialization, compared to
newornew('') - Checking whether a string ends with a specific value:
end_with?much faster than=~ormatch include?is also faster than=~ormatch
Not saying all the time you should use the fastest, code readability is the most important. Prefer clean code rather than nanosecond faster code.
Take a look at all benchmarked snippets that are available here:
https://github.com/torokmark/ruby-benchmark
For further reading about the module:
https://ruby-doc.org/stdlib-2.5.3/libdoc/benchmark/rdoc/Benchmark.html