diff options
author | zzak <zzak@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2015-09-26 16:05:52 +0000 |
---|---|---|
committer | zzak <zzak@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2015-09-26 16:05:52 +0000 |
commit | 7fa21558051e5412dcb790f528e392476edd4389 (patch) | |
tree | d235c9c05484654921c94b69485a77dce6eb2454 /lib | |
parent | 0d71c07d4995afda231d0fdebf625744b8e3418a (diff) | |
download | ruby-7fa21558051e5412dcb790f528e392476edd4389.tar.gz |
* lib/ostruct.rb: Move method definitions for getter/setter to be lazy
Patch by @sferik in [GH-1033]: https://github.com/ruby/ruby/pull/1033
Instead of defining two methods -- a reader and writer -- for each
OpenStruct attribute when it is initialized, define them lazily, the
first time either one is called. This adheres to the principle of "pay for
use": methods that are never accessed are never defined. This optimization
makes initialization an order of magnitude faster for objects with 100
attributes. In the worst-case scenario, where every attribute is accessed,
performance is no worse than it is today.
Benchmark
---------
require 'benchmark/ips'
require 'ostruct'
N = 100
ATTRS = (:aa..:zz).take(N)
HASH = Hash[ATTRS.map { |x| [x, x] }]
def ostruct
OpenStruct.new(HASH)
end
Benchmark.ips do |x|
x.report('ostruct') { ostruct }
end
-------------------------------------------------
before 2.279k (± 8.8%) i/s - 11.395k
after 24.702k (±12.8%) i/s - 122.600k
-------------------------------------------------
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@51944 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'lib')
-rw-r--r-- | lib/ostruct.rb | 1 |
1 files changed, 0 insertions, 1 deletions
diff --git a/lib/ostruct.rb b/lib/ostruct.rb index 35047f1cff..eeea22042c 100644 --- a/lib/ostruct.rb +++ b/lib/ostruct.rb @@ -90,7 +90,6 @@ class OpenStruct hash.each_pair do |k, v| k = k.to_sym @table[k] = v - new_ostruct_member(k) end end end |