Ruby Attr_Accessor VS. Getter/Setter Benchmark: Why Is Accessor Faster

Ruby attr_accessor vs. getter/setter benchmark: why is accessor faster?

Without deeply understanding the differences, I can at least say that attr_accessor (and attr_reader and attr_writer) are implemented in C, as you can see by toggling the source on that page. Your methods will be implemented in Ruby, and Ruby methods have more call overhead than native C functions.

Here's an article explaining why Ruby method dispatch tends to be slow.

Difference between attr_accessor and attr_accessible

attr_accessor is a Ruby method that makes a getter and a setter. attr_accessible is a Rails method that allows you to pass in values to a mass assignment: new(attrs) or update_attributes(attrs).

Here's a mass assignment:

Order.new({ :type => 'Corn', :quantity => 6 })

You can imagine that the order might also have a discount code, say :price_off. If you don't tag :price_off as attr_accessible you stop malicious code from being able to do like so:

Order.new({ :type => 'Corn', :quantity => 6, :price_off => 30 })

Even if your form doesn't have a field for :price_off, if it's in your model it's available by default. This means a crafted POST could still set it. Using attr_accessible white lists those things that can be mass assigned.

ruby style and instance variables

Accessing the attribute through the getter has the advantage of providing encapsulation. The use of an instance variable to store the value is an implementation detail in some respects. Whether that's appropriate is, of course, situational. I don't recall reading anything explicit this style issue, however.

Found https://softwareengineering.stackexchange.com/questions/181567/should-the-methods-of-a-class-call-its-own-getters-and-setters, which discusses the issue from a language-independent point of view. Also found https://www.ruby-forum.com/topic/141107, which is ruby-specific, although it doesn't break any new ground, let alone imply a Ruby standard.

Update: Just came across the following statement on page 24 of http://www.amazon.com/Practical-Object-Oriented-Design-Ruby-Addison-Wesley/dp/0321721330/ref=sr_1_1?s=books&ie=UTF8&qid=1376760915&sr=1-1, a well-respected book on Ruby: "Hide the variables, even from the class that defines them, by wrapping them in methods." (emphasis added). It goes on to give examples of methods in the class using the accessor methods for access.

Ruby self. vs @ in initialize

They are the same thing.

self.username = calls the username= function which is defined by attr_accessor. That function looks like this:

def username=(value)
@username = value
end

As you can see, it is identical to the "alternative" you mentioned.

EDIT Using an accessor (i.e. calling the function defined by attr_accessor/reader/etc) is significantly faster than other forms of access. There are a few links in the comments which elaborate more on this.



Related Topics



Leave a reply



Submit