Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to Fix Slow Code in Ruby - scir_full_example_benchmark.rb
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
gem "benchmark-ips"
gem "rails"
gem "sqlite3"
end
require "rails"
require "active_record"
require "benchmark/ips"
Rails.cache = ActiveSupport::Cache::MemoryStore.new
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Schema.define do
create_table :line_items do |t|
t.string :name
t.decimal :price
t.references :order
end
create_table :orders do |t|
end
end
class LineItem < ActiveRecord::Base
belongs_to :order
end
class Order < ActiveRecord::Base
has_many :line_items
def price
line_items.pluck(:price).sum
end
end
class OrderWithCachedPrice < Order
def price
Rails.cache.fetch("order_#{id}_total") { super }
end
end
order = Order.first_or_create!
order.line_items.create!(name: "Rocket Shoes", price: 97.98)
order.line_items.create!(name: "Invisible Ink", price: 5.67)
order.line_items.create!(name: "Ray Gun", price: 1_235.97)
order.line_items.create!(name: "Chunky Bacon", price: 8.99)
order_with_cache = OrderWithCachedPrice.first
Benchmark.ips do |x|
x.report("before") { order.price }
x.report("after") { order_with_cache.price }
x.compare!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.