Benchmark Ruby Code

Episode #262 by Teacher's Avatar David Kimura

Summary

It's easy to accidentally write slow code in our applications. In this episode, we look at how we can benchmark our code and examples of some methods which are slower than others.
benchmark performance ruby 12:39

Resources

Carbon - https://carbon.now.sh/
Fast Ruby - https://github.com/JuanitoFatas/fast-ruby
Code Runner - https://marketplace.visualstudio.com/items?itemName=formulahendry.code-runner

DISCLAIMER: Not all "faster" methods may be a direct replacement as the functionality could be different. Be sure to do your own testing to see if there are benefits for your specific use cases.
Download Source Code

Summary

# benchmark.rb
require 'benchmark/ips'

n = 500_000
Benchmark.ips do |x|
  x.report('for') { for i in 1..n; a = '1'; end }
  x.report('times') { n.times do; a = '1'; end }
  x.report('upto') { 1.upto(n) do; a = '1'; end }
  x.compare!
end