Skip to content

Instantly share code, notes, and snippets.

@ShopifyEng
Created May 8, 2020 14:12
Show Gist options
  • Save ShopifyEng/feebf4e53ed0e6603c0e7fd67e9f03ad to your computer and use it in GitHub Desktop.
Save ShopifyEng/feebf4e53ed0e6603c0e7fd67e9f03ad to your computer and use it in GitHub Desktop.
How to Fix Slow Code in Ruby - scir_example_benchmark.rb
# frozen_string_literal: true
require_relative "../../config/environment"
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