Skip to content

Instantly share code, notes, and snippets.

@maxcal
Last active May 17, 2021 21:12
Show Gist options
  • Save maxcal/810df7d8aec5c10c12a5669cf7ac1026 to your computer and use it in GitHub Desktop.
Save maxcal/810df7d8aec5c10c12a5669cf7ac1026 to your computer and use it in GitHub Desktop.
Arel VS gsub!
require 'benchmark'
def insert_list(table_name:, columns:, values:)
Arel::InsertManager.new.tap do |manager|
table = Arel::Table.new(table_name)
manager.into(table)
columns.each { |name| manager.columns << table[name] }
manager.values = manager.create_values_list(values)
end
end
Benchmark.bm(7) do |x|
ary = 1.upto(300000).each_slice(3).to_a
x.report('Arel') do
insert_list(
table_name: 'foos',
columns: [:a, :b, :c],
values: ary
).to_sql
end
x.report("gsub!") do
query = "insert into table_name (attr1, attr2) VALUES __SQL_VAR__ ;"
sql_var = ary.uniq.to_s.gsub('[', '(').gsub(']', ')')[1...-1] # removed first and last char to get rid of the outer array brackets
query.gsub!('__SQL_VAR__', sql_var)
end
end
user system total real
Arel 1.189341 0.008964 1.198305 ( 1.223581)
gsub! 0.621624 0.011881 0.633505 ( 0.652518)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment