Ruby Structs

True!

Finally, we have OpenStruct which is part of Ruby Core as well. At this point, you might be thinking: “Hey, looks like an OpenStruct is better in terms of melding Struct and Classsyntax and functionality.” Well, you’d be very wrong in terms of performance but, as mentioned with Class usage, I promise to expand upon this more later.

Warming up --------------------------------------

               Array     2.000  i/100ms
                Hash     1.000  i/100ms
              Struct     1.000  i/100ms
          OpenStruct     1.000  i/100ms
               Class     1.000  I/100ms

Calculating -------------------------------------

               Array     23.854  (± 0.0%) i/s -    120.000  in   5.030763s
                Hash      8.908  (±11.2%) i/s -     45.000  in   5.072652s
              Struct      4.798  (± 0.0%) i/s -     24.000  in   5.005263s
          OpenStruct      0.178  (± 0.0%) i/s -      1.000  in   5.618325s
               Class      4.230  (± 0.0%) i/s -     22.000  in   5.203019s

Comparison:

               Array:       23.9 i/s
                Hash:        8.9 i/s - 2.68x  (± 0.00) slower
              Struct:        4.8 i/s - 4.97x  (± 0.00) slower
               Class:        4.2 i/s - 5.64x  (± 0.00) slower
          OpenStruct:        0.2 i/s - 134.02x  (± 0.00) slower

Still it seems that Structs are faster, but if it was, why is not idiomatic to use them ?
And use a class for “singleton instance” and struct for the rest like in Swift.

2 Likes