Every time we need to process a hash in a method it can slow the response loop in Ruby. If you can assign your hash to a variable versus process the hash you can save time in expense methods.

1) Create the following test class named process_hash.rb

 
require 'benchmark'
 
OPTIONS = {:id => 12321, :first_name => 'Brett', :last_name => "U"}
 
class HashTest
 
  def process_input(options = {}) 
    puts Benchmark.measure { options.rehash }
  end 
 
  def process_input_as_variable(options = {}) 
    hash = options.rehash
    puts Benchmark.measure { hash }
  end 
 
end
 
h1 = HashTest.new
h1.process_input(OPTIONS)
 
h2 = HashTest.new
h2.process_input_as_variable(OPTIONS)

2) The results

 
➜  52  ruby process_hash.rb 
  0.000000   0.000000   0.000000 (  0.000012)
  0.000000   0.000000   0.000000 (  0.000006)

The second processing, where we assigned the process to a variable, is twice as fast as the first. This is a good way to reduce processing time of your application.

:)

Leave a Reply

Your email address will not be published. Required fields are marked *