Write Faster, Faster and Faster in Ruby

For the past few days, I was stocked in the Ruby performance issue. I looked for some discussion on Stack Overflow and some blogs. Fortunately, I’ve found a pretty cool project on GitHub — Fast Ruby. It’s about different performance between idioms with same purpose.

Author said that the reason write this repository is inspired by Erik Michaels’s great talk.

Measurement Tool

Use benchmark-ips (2.0+).

Idioms

Index

General
Array
Enumerable
Hash
Proc & Block
String
Range

Following is the first example of General

Parallel Assignment vs Sequential Assignment

Test code:

require 'benchmark/ips'
def fast
_a, _b, _c, _d, _e, _f, _g, _h = 1, 2, 3, 4, 5, 6, 7, 8
nil
end
def slow
_a = 1
_b = 2
_c = 3
_d = 4
_e = 5
_f = 6
_g = 7
_h = 8
nil
end
Benchmark.ips do |x|  
x.report('Parallel Assignment') { fast }
x.report('Sequential Assignment') { slow }
x.compare!
end

Result:

$ ruby -v code/general/assignment.rb
ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-darwin14]

Calculating -------------------------------------
Parallel Assignment 149.201k i/100ms
Sequential Assignment
142.545k i/100ms
-------------------------------------------------
Parallel Assignment 7.687M (± 6.9%) i/s - 38.345M
Sequential Assignment
6.320M (± 8.5%) i/s - 31.360M

Comparison:
Parallel Assignment: 7686954.1 i/s
Sequential Assignment: 6320425.6 i/s - 1.22x slower

There’s many test for the idioms. But author mention that this does not mean you can always blindly replace one with another. It depends on the context (e.g. gsub versus tr).

So, use with caution!

Reference

https://github.com/JuanitoFatas/fast-ruby

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.