Browse files

We can use the keys of the @attributes hash here and avoid a method call

  • Loading branch information...
1 parent c4809d9 commit 20ba81e47d04b0ffd510c4de9c65a439b22a00b2 @spastorino spastorino committed Dec 3, 2010
Showing with 1 addition and 1 deletion.
  1. +1 −1 activerecord/lib/active_record/base.rb
View
2 activerecord/lib/active_record/base.rb
@@ -1500,7 +1500,7 @@ def attributes=(new_attributes, guard_protected_attributes = true)
# Returns a hash of all the attributes with their names as keys and the values of the attributes as values.
def attributes
- Hash[attribute_names.map { |name| [name, read_attribute(name)] }]
+ Hash[@attributes.map { |name, _| [name, read_attribute(name)] }]
end
# Returns an <tt>#inspect</tt>-like string for the value of the

5 comments on commit 20ba81e

@pahanix

hash.map {} is a bit slower then hash.keys.map{|k| h[k]}

It is better to use
Hash[@attributes.keys.map { |name| [name, read_attribute(name)] }]

to avoid method call and sort on attributes names

require 'benchmark'
h = {}
100.times {|i| h["#{i}-#{rand(9999)}"] = rand(9999)}

Benchmark.realtime { 1000.times { Hash[h.map { |name, v| [name, v]}]}}
=> 0.169973134994507

Benchmark.realtime { 1000.times { Hash[h.keys.map { |name| [name, h[name]]}]}}
=> 0.12709903717041

@josevalim
Ruby on Rails member

Could we please, please stop micro optimizing? Most of the changes I have seen here lately won't show a real performance improvement once it goes through a request stack. Our focus should be in code readability and maintainability.

@pahanix

Those all micro optimizations started from lolinject. For me (personally) inject was most readable here. But each was most readable for all people.

@pahanix

Those all micro optimizations started from lolinject. For me (personally) inject was most readable here. But each was most readable for all people.

@josevalim
Ruby on Rails member

Hahaha, lolinject was funny! I was not talking about your comment, but the thing in general. :)

Please sign in to comment.