From: aero6dof@... (Alan Chen) Date: 2003-10-03T02:07:07+09:00 Subject: Re: Array and hash iteration questions "Robert Klemme" wrote in message news:... > No need to use a Hash for this... > > Number = 0 > Errors = 1 > > cases[case][Number] += 1 > cases[case][Errors] += 1 if arr[OFFSET] =~ /Error/ > > I might be a bit pricky, but storing the array ref saves one hash lookup. > It *can* affect performance if you have a large amount of cases... (see > below; although the timing is dominated by the iteration here, you can see > that the array is faster) I'm not sure if my testing method is quite consistent, but making a specific record object looks like it could speed things up even more... >ruby -rprofile lookups.rb % cumulative self self total time seconds seconds calls ms/call ms/call name 73.74 13.08 13.08 3 4359.00 5911.67 Integer#upto 14.47 15.64 2.57 100001 0.03 0.03 Hash#[] 11.79 17.73 2.09 100001 0.02 0.02 Array#[] 0.08 17.75 0.01 1 15.00 15.00 Profiler__.start_profile 0.00 17.75 0.00 1 0.00 17735.00 #toplevel 0.00 17.75 0.00 1 0.00 0.00 Class#inherited 0.00 17.75 0.00 1 0.00 1329.00 Object#testObj 0.00 17.75 0.00 2 0.00 8203.00 Object#test 0.00 17.75 0.00 1 0.00 0.00 TestObj#initialize 0.00 17.75 0.00 1 0.00 8203.00 Object#testArray 0.00 17.75 0.00 9 0.00 0.00 Module#method_added 0.00 17.75 0.00 1 0.00 8203.00 Object#testHash 0.00 17.75 0.00 1 0.00 0.00 Module#attr_accessor 0.00 17.75 0.00 1 0.00 0.00 Class#new >type lookups.rb def test(coll) 0.upto( 100000 ) do coll[2] end end def testHash test( { 0 => 0, 1 => 1, 2 => 2 } ) end def testArray test( [0, 1, 2] ) end # a simple record class... class TestObj attr_accessor :num, :err def initialize @num = 0 @err = 0 end end def testObj to = TestObj.new 0.upto( 100000 ) do to.err end end testHash testArray testObj > 10:17:02 [ruby]: ruby -rprofile lookups.rb > % cumulative self self total > time seconds seconds calls ms/call ms/call name > 62.50 13.93 13.93 2 6962.50 11140.50 Integer#upto > 26.22 19.77 5.84 100001 0.06 0.06 Hash#[] > 11.28 22.28 2.51 100001 0.03 0.03 Array#[] > 0.07 22.30 0.01 1 15.00 15.00 > Profiler__.start_profile > 0.00 22.30 0.00 2 0.00 11140.50 Object#test > 0.00 22.30 0.00 3 0.00 0.00 Module#method_added > 0.00 22.30 0.00 1 0.00 11171.00 Object#testArray > 0.00 22.30 0.00 1 0.00 22281.00 #toplevel > 0.00 22.30 0.00 1 0.00 11110.00 Object#testHash