From: bwv549 Date: 2007-04-03T23:05:07+09:00 Subject: Re: implementing an array based class Thanks for the pointers. I'd love to know how to do proper memory benchmarking. It does not seem trivial, I guess. Regarding object initialization, I guess I'm really interested in total time to initialize the object and fill in all attributes with values (as this is what I'm going to be facing before I can use any of the objects). I've incorporated this aspect into a similar benchmark for comparison: Rehearsal -------------------------------------------------- Class1 5.666667 0.533333 6.200000 ( 3.730552) Class2 5.983333 0.516667 6.500000 ( 3.904695) Struct 3.950000 0.250000 4.200000 ( 2.518688) ArrayBased 2.033333 0.350000 2.383333 ( 1.431213) Array.new 2.100000 0.316667 2.416667 ( 1.443011) Array [] 0.833333 0.266667 1.100000 ( 0.671233) ---------------------------------------- total: 22.800000sec user system total real Class1 5.550000 0.600000 6.150000 ( 3.686555) Class2 5.716667 0.666667 6.383333 ( 3.834078) Struct 3.883333 0.316667 4.200000 ( 2.527558) ArrayBased 2.166667 0.266667 2.433333 ( 1.445458) Array.new 2.150000 0.300000 2.450000 ( 1.474190) Array [] 0.900000 0.233333 1.133333 ( 0.684567) ---------------------------------------------------- #!/usr/bin/ruby require 'benchmark' include Benchmark attribute_array = (1...7).to_a class Class1 def initialize(attribute_array) (@f1, @f2, @f3, @f4, @f5, @f6, @f7) = attribute_array end end class Class2 def initialize(f1=nil, f2=nil, f3=nil, f4=nil, f5=nil, f6=nil, f7=nil) @f1=f1 @f2=f2 @f3=f3 @f4=f4 @f5=f5 @f6=f6 @f7=f7 end end StructClass = Struct.new(:f1, :f2, :f3, :f4, :f5, :f6, :f7) filled_in = StructClass.new( *attribute_array ) class ArrayBased < Array end filled_in = ArrayBased.new(attribute_array) REP = 1_000_000 bmbm(15) do |re| re.report("Class1") { REP.times { Class1.new(attribute_array) } } re.report("Class2") { REP.times { Class2.new(*attribute_array) } } re.report("Struct") { REP.times { StructClass.new(*attribute_array) } } re.report("ArrayBased") { REP.times { ArrayBased.new(attribute_array) } } re.report("Array.new") { REP.times { Array.new(attribute_array) } } re.report("Array []") { REP.times { [*attribute_array] } } end ---------------------------------------------------- For speed, at least, my initialize observations appear to hold (in this benchmark, anyway). Ordered by fastest filled object creation: Array [], ArrayBased & Array.new, Struct, Class Kind regards, john