Skip to content

Instantly share code, notes, and snippets.

@coryodaniel
Created December 8, 2015 17:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coryodaniel/8ff19ca7ec19aa38bbba to your computer and use it in GitHub Desktop.
Save coryodaniel/8ff19ca7ec19aa38bbba to your computer and use it in GitHub Desktop.
Rails 5 ActiveRecord Query Building: Array vs Hash
require 'benchmark'

n = 100_000
Benchmark.bm do |x|
  x.report('Array interpolation: 1 param'){ 
    n.times { User.where("email = ?", "user@example.com").to_sql }
  }

  x.report('Array interpolation: 3 params'){ 
    n.times { User.where("email = ? and password = ? and account_status > ?", "user@example.com", "123456", :ok).to_sql }
  }  
  
  x.report('Hash interpolation: 1 param'){ 
    n.times { User.where("email = :email", email: "user@example.com").to_sql }
  }

  x.report('Hash interpolation: 3 params'){ 
    n.times {
      User.where(
        "email = :email and password = :password and account_status = :status", 
        email: "user@example.com",
        password: '123456',
        status: :ok
      ).to_sql
    }
  }
end
Test user system total real
Array interpolation: 1 param 8.050000 0.020000 8.070000 ( 8.057007)
Array interpolation: 3 params 8.960000 0.000000 8.960000 ( 8.969475)
Hash interpolation: 1 param 8.330000 0.020000 8.350000 ( 8.345027)
Hash interpolation: 3 params 9.930000 0.010000 9.940000 ( 9.943917)
@coryodaniel
Copy link
Author

I like using hashes, its easier to read. One of my friends told me it was slow. I'll take readability over saving 2 seconds per 100_000 queries.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment