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 ...
Get Addison-Wesley Professional Ruby Series Writing Efficient Ruby Code now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.