Skip to content

Instantly share code, notes, and snippets.

@dmeremyanin
Created July 28, 2014 08:07
Show Gist options
  • Save dmeremyanin/08d12f9a9daad5ddac11 to your computer and use it in GitHub Desktop.
Save dmeremyanin/08d12f9a9daad5ddac11 to your computer and use it in GitHub Desktop.
require 'benchmark/ips'
require 'active_support/hash_with_indifferent_access'
require 'active_support/core_ext/hash'
begin
@attributes = [{ 'id' => 1, 'name' => 'Julia', 'created_at' => Time.now }] * 1000
@mapping = { 'id' => 'user_id' }
def sleep
super 0.00000001 # typecasting simulation
end
def pluck_attributes1
@attributes.map do |attributes|
attributes.each do |key, value|
attributes[key] = value
sleep
end
end
end
def pluck_attributes_mapping
@attributes.map do |attributes|
mapped = {}
attributes.each do |key, value|
key_name = @mapping[key] || key
mapped[key_name] = value
sleep
end
mapped
end
end
def pluck_attributes_hwia
@attributes.map do |attributes|
mapped = HashWithIndifferentAccess.new
attributes.each do |key, value|
mapped[key] = value
sleep
end
mapped
end
end
def pluck_attributes_hwia_mapping
@attributes.map do |attributes|
mapped = HashWithIndifferentAccess.new
attributes.each do |key, value|
mapped[@mapping[key] || key] = value
sleep
end
mapped
end
end
Benchmark.ips do |x|
x.report('original') do
pluck_attributes1
end
x.report('mapping') do
pluck_attributes_mapping
end
x.report('hwia') do
pluck_attributes_hwia
end
x.report('hwia+mapping') do
pluck_attributes_hwia_mapping
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment