Last active
November 19, 2019 10:52
-
-
Save pioz/2bf247756f3d88aca2c027a5bee29cf3 to your computer and use it in GitHub Desktop.
Benchmark single join vs 2 with pluck
This file contains hidden or 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
| require 'active_record' | |
| require 'activerecord-import' | |
| require 'mysql2' | |
| require 'benchmark' | |
| ActiveRecord::Base.establish_connection( | |
| adapter: 'mysql2', | |
| host: 'localhost', | |
| username: 'root', | |
| database: 'joiner' | |
| ) | |
| class ApplicationRecord < ActiveRecord::Base | |
| self.abstract_class = true | |
| end | |
| class Author < ApplicationRecord | |
| has_many :posts, dependent: :destroy | |
| end | |
| class Post < ApplicationRecord | |
| belongs_to :author | |
| end | |
| def migrate | |
| ActiveRecord::Schema.define do | |
| create_table(:authors) do |t| | |
| t.string :name | |
| t.integer :power_level | |
| end | |
| create_table(:posts) do |t| | |
| t.references :author, null: false, foreign_key: true | |
| t.string :title | |
| t.text :content | |
| end | |
| add_index :authors, :power_level | |
| end | |
| end | |
| def populate | |
| authors = [] | |
| posts = [] | |
| 10_000.times do |i| | |
| authors << Author.new(id: i + 1, name: "Author #{i}", power_level: rand(3)) | |
| 100.times do |j| | |
| posts << Post.new(title: "Post #{i}-#{j}", author_id: i + 1) | |
| end | |
| end | |
| Author.import!(authors) | |
| Post.import!(posts) | |
| end | |
| migrate | |
| populate | |
| puts 'Populated!' | |
| n = 5000 | |
| Benchmark.bm do |benchmark| | |
| benchmark.report("With join\t\t") do | |
| n.times do | |
| Post.joins(:author).where(authors: { power_level: rand(3) }) | |
| end | |
| end | |
| benchmark.report("With nested select\t") do | |
| n.times do | |
| Post.where(author: Author.where(power_level: rand(3))) | |
| end | |
| end | |
| benchmark.report("With pluck\t\t") do | |
| n.times do | |
| author_ids = Author.where(power_level: rand(3)).pluck(:id) | |
| Post.where(author_id: author_ids) | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment