Matthew Lindfield Seager

Matthew Lindfield Seager

OpenStructs are SLOW, at least according to an article from a few years ago -…

I can’t vouch for how realistic the test is but running it again today as is shows that hashes have improved significantly. They are now faster than classes and ONE HUNDRED times faster than OpenStructs in this scenario.

                    user     system      total        real
hash:           1.066739   0.005513   1.072252 (  1.098668)
openstruct:   107.167921   0.261942 107.429863 (107.722112)
struct:         2.185639   0.002021   2.187660 (  2.191069)
class:          1.710577   0.001941   1.712518 (  1.715534)

Don’t prematurely optimise but if you’re doing anything that involves a lot of OpenStruct creation (which is where the overhead lies) it might be best to choose a different data structure.

On a related note, I’m struggling to figure out when passing around a loosely defined OpenStruct would ever be preferable to a class. Seems like an OpenStruct would unnecessarily couple the creator and the consumer.

More academically, I also re-ran the other benchmark, this time increasing the count to 100,000,000 and adding in a method that used positional arguments.

                 user     system      total        real
keywords:   23.196255   0.054049  23.250304 ( 23.366176)
positional: 19.664959   0.044322  19.709281 ( 19.789321)
hash:       31.235545   0.039376  31.274921 ( 31.328692)

In this case I was gratified to see that keyword arguments are only slightly slower than positional ones. I much prefer keyword arguments as they are clearly defined in the method signature, raise helpful ArgumentErrors when you leave them out or type them wrong and are much easier to reason about when reading code where the method gets called.