Last active
November 23, 2018 04:39
-
-
Save dvandersluis/ed04ed0a56407b6626237c61592288c0 to your computer and use it in GitHub Desktop.
Map vs Pluck on a collection of ActiveRecords
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark/ips' | |
photo = Photo.last | |
arr = [photo] | |
Benchmark.ips do |x| | |
x.report('map') { arr.map(&:id) } | |
x.report('pluck') { arr.pluck(:id) } | |
x.compare! | |
end | |
# Warming up -------------------------------------- | |
# map 99.386k i/100ms | |
# pluck 43.925k i/100ms | |
# Calculating ------------------------------------- | |
# map 1.453M (± 5.5%) i/s - 7.255M in 5.011617s | |
# pluck 516.576k (± 5.5%) i/s - 2.592M in 5.034014s | |
# Comparison: | |
# map: 1453097.0 i/s | |
# pluck: 516576.3 i/s - 2.81x slower |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# It seems weird that pluck is so much slower than map, why is this? | |
# | |
# Enumerable#pluck does this: | |
# | |
# def pluck(*keys) | |
# if keys.many? | |
# map { |element| keys.map { |key| element[key] } } | |
# else | |
# map { |element| element[keys.first] } | |
# end | |
# end | |
# | |
# So we can benchmark calling the method directly vs calling it using a hash index: | |
Benchmark.ips do |x| | |
x.report('method') { photo.id } | |
x.report('[]') { photo[:id] } | |
x.compare! | |
end | |
# Warming up -------------------------------------- | |
# method 107.402k i/100ms | |
# [] 50.153k i/100ms | |
# Calculating ------------------------------------- | |
# method 1.701M (±12.8%) i/s - 8.377M in 5.029031s | |
# [] 625.839k (± 8.9%) i/s - 3.109M in 5.012088s | |
# Comparison: | |
# method: 1700735.1 i/s | |
# []: 625839.1 i/s - 2.72x slower |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment