O'Reilly logo

Addison-Wesley Professional Ruby Series Writing Efficient Ruby Code by Dr. Stefan Kaes

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter . Patterns

Instance Variables versus Accessors

As described earlier, method calls in Ruby usually involve a method lookup in a hash structure, which is considerably more expensive than a simple machine-supported subroutine call in statically compiled languages. We therefore want to avoid method calls as much as possible.

Accesses to class/module attributes declared via attr_accessor, attr_reader, or attr_writer all involve method calls. We can reduce the overhead of attribute access by using the corresponding instance variables directly. So, instead of attribute, we’d write @attribute. And instead of

self.attribute = expr

we’d write

@attribute = expr

which results in shorter code as well.

Obviously, this transformation breaks encapsulation and ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required