In profiling some code recently, we found a spot where we were using OpenStruct to handle parsed JSON coming back from a web service. OpenStruct is nice, because it allows you to address the returned object like a normal Ruby class using dot notation (IE my_class.name = "foo"). We read the following warning in the docs:
This should be a consideration if there is a concern about the performance of the objects that are created, as there is much more overhead in the setting of these properties compared to using a Hash or a Struct.
However, we didn't realize just how bad performance would be. Check out this benchmark comparing Hash, OpenStruct, Struct, and Class:
OpenStruct uses Ruby's method_missing and define_method to simulate "normal" objects, so if you are using these methods frequently in code, check to see if they are really necessary.
Seeing that classes outperformed hashes by a significant margin, I decided to investigate using Ruby 2.0's new keyword arguments when I needed optional parameters on methods. My assumption was that calling a method and passing in the arguments as a hash would incur some performance penalty as each method invocation would result in a new hash being instantiated.
I was surprised to see that using hashes outperformed Ruby 2.0's native keyword arguments by quite a bit:
Update - June 2015
# Using Ruby 2.2.1p85 on a MacBook Pro (Retina Early 2015) w/ 3.1 GHz i7
user system total real hash: 7.980000 0.510000 8.490000 ( 8.631545) keywords: 2.940000 0.060000 3.000000 ( 3.038953)
user system total real hash: 5.490000 0.540000 6.030000 ( 6.396844) openstruct: 127.070000 1.610000 128.680000 (131.303417) struct: 3.630000 0.040000 3.670000 ( 3.691814) class: 2.350000 0.010000 2.360000 ( 2.415393)