From: janosch-x via ruby-core Date: 2023-05-27T17:09:12+00:00 Subject: [ruby-core:113686] [Ruby master Misc#19693] Data initialization is significantly slower than Struct Issue #19693 has been updated by janosch-x (Janosch M��ller). > I suppose it wouldn't hurt. I think its beautiful ���� Another option could be to bypass the initializer by default and only patch it into a Data subclass when `initialize` is redefined (as detected via `method_added` or so). > Defining a `new` singleton method on the Data subclass, in Ruby and with explicit keyword arguments should be able to then use the literal kwargs optimization @Eregon Wouldn't that require exposing some kind of alternate, non-freezing initializer to Ruby, or some setter methods? This seems to go a bit against the immutable spirit of the class. Also, wouldn't defining `new` in Ruby slow down initialization with positional/list arguments? Maybe the solution would rather be to auto-define a `keyword_initialize` method or so in Ruby and let `new`, still in C, delegate to that method when given kwargs? BTW using literal kwargs in Ruby also makes struct initialization with keywords 3 times faster: ```ruby require 'benchmark/ips' S1 = Struct.new(:a, :b, :c, :d, :e, :f, :g, :h, :i, :j) S2 = Struct.new(:a, :b, :c, :d, :e, :f, :g, :h, :i, :j) class << S2 alias orig_new new def new(a: nil, b: nil, c: nil, d: nil, e: nil, f: nil, g: nil, h: nil, i: nil, j: nil) orig_new(a, b, c, d, e, f, g, h, i, j) end end Benchmark.ips do |x| x.report('ckw') { S1.new(a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10) } x.report('rubykw') { S2.new(a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10) } x.compare! end; 1 # rubykw: 4510892.9 i/s # ckw: 1377423.3 i/s - 3.27x slower ``` ---------------------------------------- Misc #19693: Data initialization is significantly slower than Struct https://bugs.ruby-lang.org/issues/19693#change-103331 * Author: janosch-x (Janosch M��ller) * Status: Closed * Priority: Normal ---------------------------------------- Maybe there is potential to make it as fast as Struct? ```ruby require 'benchmark/ips' S = Struct.new(:a, :b, :c, :d, :e, :f, :g, :h, :i, :j) D = Data.define(:a, :b, :c, :d, :e, :f, :g, :h, :i, :j) Benchmark.ips do |x| x.report('Struct') { S.new(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) } x.report('Data') { D.new(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) } x.compare! end; 1 # => [...] # => Struct: 6916530.4 i/s # => Data: 1507259.5 i/s - 4.59x slower ``` -- https://bugs.ruby-lang.org/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/postorius/lists/ruby-core.ml.ruby-lang.org/