Today I Learned

hashrocket A Hashrocket project

Accessor Performance Gap

This week I learned that attr_reader is more performant than a simple getter method.

Here’s a gist from five years ago where Aaron Patterson explains:

I ran that same benchmarking script today on Ruby 2.2.3. The gap has narrowed, but still exists:

Rehearsal -----------------------------------------------
method        0.070000   0.000000   0.070000 (  0.074840)
attr_reader   0.050000   0.000000   0.050000 (  0.052603)
-------------------------------------- total: 0.120000sec

                  user     system      total        real
method        0.070000   0.000000   0.070000 (  0.072229)
attr_reader   0.050000   0.000000   0.050000 (  0.053374)

I like attr_reader because it’s a Ruby convention and is one line instead of three. Now, I also like its performance relative to a getter.

h/t Josh Davey

See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.