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 | 68d4cbf33edab7b7fd5c1ae21755cd0b7d26d279 (patch) | |
tree | d235c9c05484654921c94b69485a77dce6eb2454 | |
parent | b772c42f6435ea67474bb2511758c03b77ae239e (diff) | |
download | ruby-68d4cbf33edab7b7fd5c1ae21755cd0b7d26d279.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
-rw-r--r-- | ChangeLog | 5 | ||||
-rw-r--r-- | lib/ostruct.rb | 1 |
2 files changed, 5 insertions, 1 deletions
@@ -1,3 +1,8 @@ +Sun Sep 27 00:34:31 2015 Zachary Scott <zzak@ruby-lang.org> + + * 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 + Fri Sep 25 10:07:25 2015 SHIBATA Hiroshi <hsbt@ruby-lang.org> * lib/net/http.rb: removed unused variable. It's removed at r13648. 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 |