• G
    PERF: Don't create a Relation when it is not needed. · 69de09c5
    Guo Xiang Tan 提交于
    Benchmark script used:
    ```
    begin
      require 'bundler/inline'
    rescue LoadError => e
      $stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler'
      raise e
    end
    
    gemfile(true) do
      source 'https://rubygems.org'
      gem 'rails', path: '~/rails' # master against ref "f1f0a3f8"
      gem 'arel', github: 'rails/arel', branch: 'master'
      gem 'rack', github: 'rack/rack', branch: 'master'
      gem 'sass'
      gem 'sprockets-rails', github: 'rails/sprockets-rails', branch: 'master'
      gem 'sprockets', github: 'rails/sprockets', branch: 'master'
      gem 'pg'
      gem 'benchmark-ips'
    end
    
    require 'active_record'
    require 'benchmark/ips'
    
    ActiveRecord::Base.establish_connection('postgres://postgres@localhost:5432/rubybench')
    
    ActiveRecord::Migration.verbose = false
    
    ActiveRecord::Schema.define do
      create_table :users, force: true do |t|
        t.string :name, :email
        t.timestamps null: false
      end
    end
    
    class User < ActiveRecord::Base; end
    
    attributes = {
      name: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
      email: "foobar@email.com",
    }
    
    1000.times { User.create!(attributes) }
    
    Benchmark.ips(5, 3) do |x|
      x.report('all') { User.all }
    end
    
    key =
      if RUBY_VERSION < '2.2'
        :total_allocated_object
      else
        :total_allocated_objects
      end
    
    before = GC.stat[key]
    User.where(name: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
    after = GC.stat[key]
    puts "Total Allocated Object: #{after - before}"
    
    ```
    
    Before:
    ```
    Calculating -------------------------------------
                     all    17.569k i/100ms
    -------------------------------------------------
                     all    190.854k (± 3.3%) i/s -    966.295k
    Total Allocated Object: 85
    ```
    
    After:
    ```
    Calculating -------------------------------------
                     all    22.237k i/100ms
    -------------------------------------------------
                     all    262.715k (± 5.5%) i/s -      1.312M
    Total Allocated Object: 80
    ```
    69de09c5
default.rb 5.0 KB