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?

  1. Object nil check: unless obj though .nil? is nicer and readable
  2. For looping: while or until
  3. Array creation: [] is unbeatable
  4. Array with values: (...).to_a is the fastest
  5. Array emptyness check: .empty? is much faster than arr == []
  6. For extending an array: + is faster than concat
  7. Iterate over a sorted array and compare its elements is faster than the same with an unsorted array
  8. {} is faster than new
  9. In case of Hash use .empty? to check emptyness, and readable as well
  10. For adding new element [] and store are almost the same, merge is far slowest
  11. Iterate over a Hash, get the keys first by .keys faster than each, each_keys or each_pair
  12. For selecting elements, use keep_if or delete_if, they are almost on the same performance. select is slow
  13. Check whether a key exists, use []. .has_key? is far slower
  14. Empty string assign is the faster string initialization, compared to new or new('')
  15. Checking whether a string ends with a specific value: end_with? much faster than =~ or match
  16. include? is also faster than =~ or match

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