-
-
Save ShopifyEng/feebf4e53ed0e6603c0e7fd67e9f03ad to your computer and use it in GitHub Desktop.
How to Fix Slow Code in Ruby - scir_example_benchmark.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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