Hashugar (Hash Sugar)

Build Status

Nested OpenStruct alternative optimized for speed especially for many short-lived objects (e.g. results from db).

Usage

$ gem install hashugar


hashugar = {:a => 1, 'b' => {:c => 2, :d => [3, 4, {:e => 5}]}}.to_hashugar
hashugar.a # => 1
hashugar.b.c # => 2
hashugar.b.d.last.e # => 5

How fast is it?

Let's compare to the competitors - OpenStruct, Hashr

$ rake bench

Ruby 2.1.3 benchmark

OpenStruct create small hash and access once
                       110766.3 (

Why is it so fast?

OpenStruct defines a method using metaprogramming on first access, but this is a slow operation. Hashr is converting whole hash on initialization which is slower when you don't need to access all keys and nested keys. Hashugar uses method_missing, which is slower in the long run, but faster for short-lived objects, it's also lazy so there is no precomputation/conversion step.