views:

63

answers:

1

Is there any performance overhead that you take on when using Structs (as compared to Arrays, Hashes, etc.) in Ruby?

+1  A: 

I tried running the following several times (following Jörg's comment this has been updated to use a fixed variable for the value instead of creating lots of strings):

require 'benchmark'

Example = Struct.new("Example", :value)

struct = Example.new
hash = {}
value = "The value"

n = 5000000
Benchmark.bm do |m|
  # test assignment and access for Hash and Struct
  m.report { n.times do; hash[:value] = value; end }
  m.report { n.times do; struct.value = value; end }
end

Update

It seems with a large enough value of n the Struct is slightly slower but I can't imagine this would be noticeable or an issue in practice.

mikej
I wouldn't be too surprised if your benchmark was dominated by the overhead of creating (and garbage collecting!) 2 million strings.
Jörg W Mittag
Good point. Do you think it would be a better measure if we used a single string for the value instead of creating new ones each time? (I will edit the answer)
mikej
No, I think it would be better if the OP simply did the work himself, benchmarking his *actual* code in his *actual* environment on his *actual* Ruby implementation under *realistic* load. Because everything else is just bogus.
Jörg W Mittag