Ruby 1.8: SimpleDelegator is very slow

Posted . Visible to the public.

If you're still working on ruby 1.8, you should know that using SimpleDelegator is often prohibitively slow. I have seen SimpleDelegator.new(myActiveRecordModel) take 50ms+ per instantiation.

The reason is that SimpleDelegator actually loops through all methods of an object and does a define_method. Which is not exactly fast.

To speed up your code, you can often simply replace

class MyUserDecorator < SimpleDelegator
   ...
end

with

class MyUserDecorator < DelegateClass(User)
   ...
end

This will obviously not work if you pass in anything else than a user object, and hence you can no longer easily chain delegators.

Tobias Kraze
License
Source code in this card is licensed under the MIT License.
Posted by Tobias Kraze to makandra dev (2013-12-04 17:10)