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) |
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.