Accessing ActiveRecord attribute slower than local variable
I was deep in a performance optimization flow when I stumbled upon this part in a ruby-prof graph:
- 17.59% (73.45%) SomeTable::GeneratedAttributeMethods#some_attribute [30263106 calls, 44665545 total]
- 15.24% (86.62%) ActiveRecord::AttributeMethods::Read#_read_attribute [30263106 calls, 49437307 total]
- 11.82% (77.58%) ActiveModel::AttributeSet#fetch_value [30263106 calls, 49068748 total]
- 5.44% (46.06%) ActiveModel::AttributeSet#[] [30263106 calls, 49303667 total]
- 2.32% (42.58%) Hash#[] [30263106 calls, 72892138 total]
- 2.05% (17.36%) ActiveModel::Attribute#value [30263106 calls, 49274896 total]
ActiveRecord stores attributes internally in a hash, which is more expensive than I expected.