From: Alex Fenton Date: 2007-10-17T02:10:05+09:00 Subject: Re: Struct is slow Wayne Magor wrote: > I have a script in which I was using a 2-element array where a struct > would be used in another language, so I decided to give the Ruby class > Struct a try. > > My script went from taking 2 seconds to taking 27 seconds from this > simple change! This doesn't sound likely, even if your script did nothing else but use the Struct class. I'd look elsewhere for the source of slowness (try running your script with -rprofile). A quick benchmark suggests that Struct is somewhat slower to instantiate (+100%), marginally slower to set values in (+33%), and the same speed to fetch values from as an Array: BENCHMARK: require 'benchmark' GC.disable Foo = Struct.new(:foo, :bar) repetitions = 500_000 puts 'struct-init', Benchmark::measure { repetitions.times { f = Foo.new('x', 666) } } puts 'array-init', Benchmark::measure { repetitions.times { f = ['x', 666] } } puts 'struct-get', Benchmark::measure { f = Foo.new('x', 666) repetitions.times { g = f.foo } } puts 'array-get', Benchmark::measure { f = ['x', 666] repetitions.times { g = f[0] } } puts 'struct-set', Benchmark::measure { f = Foo.new('x', 666) repetitions.times { f.foo = 'y' } } puts 'array-set', Benchmark::measure { f = ['x', 666] repetitions.times { f[0] = 'y' } } __END__ RESULTS (ruby 1.8.4 (2005-12-24) [i386-mswin32]) struct-init 1.359000 0.031000 1.390000 ( 1.390000) array-init 0.563000 0.016000 0.579000 ( 0.579000) struct-get 0.281000 0.000000 0.281000 ( 0.281000) array-get 0.297000 0.000000 0.297000 ( 0.297000) struct-set 0.422000 0.000000 0.422000 ( 0.422000) array-set 0.281000 0.000000 0.281000 ( 0.281000) alex