From 68d4cbf33edab7b7fd5c1ae21755cd0b7d26d279 Mon Sep 17 00:00:00 2001 From: zzak Date: Sat, 26 Sep 2015 16:05:52 +0000 Subject: * 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 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- ChangeLog | 5 +++++ lib/ostruct.rb | 1 - 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/ChangeLog b/ChangeLog index 2023dd9f9a..f5b97353f8 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +Sun Sep 27 00:34:31 2015 Zachary Scott + + * 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 * 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 -- cgit v1.2.3