I sense a series on ActiveRecord optimizations upon us. Today lets look at how we can test the insert of an ActiveRecord object into our database.   require "benchmark"   Benchmark.bm(7) do |x| x.report { (1..10000).each_slice(100) { |a| a.each_with_index {|p, idx| Product.create!(title: "Shoe-#{idx}", store_id: 1) }}} x.report { (1..10000).each_with_index { |p, idx| Product.create!(title: "Shoe-#{idx}", store_id: 1) } } x.report { (1..10000).each { |i| Product.create!(title: "Shoe-#{i}", store_id: 1) } } end   #=> [   #<Benchmark::Tms:0x007fa71863ed60 @label="", @real=24.679326, @cstime=0.0, @cutime=0.0, @stime=4.780000000000001, @utime=16.759999999999998, @total=21.54>,   #<Benchmark::Tms:0x007fa719869418 @label="", @real=24.60898, @cstime=0.0, @cutime=0.0, @stime=4.76, @utime=16.750000000000007, @total=21.510000000000005>,   #<Benchmark::Tms:0x007fa7162f8658 @label="", @real=24.802445, @cstime=0.0, @cutime=0.0, @stime=4.75, @utime=16.92, @total=21.67>   ] Our benchmarks around the Array show us the looping isn’t the issue (reducing the loops doesn’t have a[…]

Ruby scripts can become expensive quickly and this handy method can let you know if something is getting out of control. This script will read out of the %cpu on a OSX system. def cpu_usage cpu = `ps -o %cpu #{$$}` cpu.strip.gsub(/\n/, ":") end   p cpu_usage #=> "%CPU: 0.0"   (0..25000).each do |int| p cpu_usage end   #=> %CPU: 34.7" #=> %CPU: 35.1" #=> … There are many other ps commands you could place here that should help to gain an understanding of how the system is reacting to you code. :)

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)[…]