Episodes

Resources

Summary

# Gemfile
group :development do
  ...
  gem 'get_process_mem'
end

gem 'activerecord-import'

# db/seeds.rb
require 'csv'

def print_usage
  mb = GetProcessMem.new.mb
  "Memory Usage: #{mb.round}MB"
end

puts "Importing Individual Rows"
start_time = Time.now
CSV.foreach("#{Rails.root}/db/data.csv") do |u|
  user = User.new(
                  username: u[0],
                  first_name: u[1],
                  last_name: u[2],
                  email: u[3],
                  address_line_one: u[4],
                  address_city: u[5],
                  address_state: u[6],
                  birthday: u[7],
                  phone_home: u[8],
                  phone_work: u[9],
                  phone_cell: u[10]
  )
  user.save!
end
end_time = Time.now
puts "Time elapsed: #{end_time - start_time}s | #{print_usage}"

puts "Importing Wrapped in Transaction"
start_time = Time.now
User.transaction do
  CSV.foreach("#{Rails.root}/db/data.csv") do |u|
    user = User.new(
                    username: u[0],
                    first_name: u[1],
                    last_name: u[2],
                    email: u[3],
                    address_line_one: u[4],
                    address_city: u[5],
                    address_state: u[6],
                    birthday: u[7],
                    phone_home: u[8],
                    phone_work: u[9],
                    phone_cell: u[10]
    )
    user.save!
  end
end
end_time = Time.now
puts "Time elapsed: #{end_time - start_time}s | #{print_usage}"

puts "Importing in Bulk"
start_time = Time.now
users = CSV.read("#{Rails.root}/db/data.csv")
columns = %i[username first_name last_name email address_line_one address_city address_state birthday phone_home phone_work phone_cell]
User.import columns, users, validate: false
end_time = Time.now
puts "Time elapsed: #{end_time - start_time}s | #{print_usage}"