Timing ruby methods

I recently started working on an old project (a couple years of dev with several different teams and different preferences on style).  It has a full test suite which is slow (~25 minutes).  And there are pages which suffer from over-wrought code that makes ruby spin and spin to get data.

In an effort to speed things up, I developed several little timing tests to see what ruby does well, and how we can improve things by using the right ruby convention or method.

I thought I should share the learnings.

The basic takeaways are:

  1. join strings with “+”, not join or interpolation (https://github.com/rcode5/ruby-join-strings-speed-test)
  2. keyword arguments for methods is slower (by ~15%) (https://github.com/rcode5/ruby-keyed-arguments-speed-test)
  3. services that are not purely class methods are slower (https://github.com/rcode5/ruby-class-v-instance-speed-test)
  4. matching strings with == (and downcase) is faster than regex (https://github.com/rcode5/ruby-match-strings-speed-test)
  5. .sum is equivalent to .reduce or .inject until ruby 2.4 where .sum is way faster (https://github.com/rcode5/ruby-sum-numbers-speed-test)

Check out the repositories for more details.

Advertisements