Ruby is not Javascript - Benchmarking Hash/Struct Performance

Recently I was using ruby-prof to profile a Rails app and find slow methods. I found a snippet that thoughtlessly used a Hash as a simple object structure in a recursive method. I then recalled something I read back when I was learning Ruby: “Ruby is not Javascript”. By replacing it with a Struct (for example), I got much better performance:

#!/usr/bin/env ruby

require 'benchmark'

DataStruct = Struct.new(:first, :second, :third)
#DataHash = {first: nil, second: nil, third: nil}

how_many = 10000000

Benchmark.bm do |bm|

  bm.report do
    how_many.times do |i|
      d = DataStruct.new(i, i, i)
      d.first
      d.second
      d.third
    end
  end

  bm.report do
    how_many.times do |i|
      d = {first: i, second: i, third: i}
      d[:first]
      d[:second]
      d[:third]
    end
  end
end

Results:

$ ./hash_struct_benchmark.ruby
       user     system      total        real
   2.970000   0.000000   2.970000 (  2.971385)
   5.610000   0.000000   5.610000 (  5.610265)

How I felt:

face palm

Updated: