Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active December 14, 2019 03:06
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 havenwood/0b404e201fd9c095c3269bfb8ebb4347 to your computer and use it in GitHub Desktop.
Save havenwood/0b404e201fd9c095c3269bfb8ebb4347 to your computer and use it in GitHub Desktop.
require 'benchmark/ips'
Benchmark.ips do |x|
array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
x.report('transpose') { array.transpose.product(array.transpose).flatten(1) }
x.report('proc') { :product.to_proc.call(*array) }
x.report('reduce') { array.reduce(&:product).map(&:flatten) }
x.report('then') { array.then { |head, *tail| head.product *tail } }
x.report('slices') { array[0].product(array[1..-1]) }
x.report('endless first slices') { array.first.product(array[1..]) }
x.report('endless slices') { array[0].product(array[1..]) }
x.compare!
end
Calculating -------------------------------------
transpose 430.108k (± 2.9%) i/s - 2.151M in 5.004655s
proc 485.482k (± 2.8%) i/s - 2.441M in 5.031551s
reduce 61.228k (± 2.6%) i/s - 309.320k in 5.055422s
then 466.964k (± 6.8%) i/s - 2.350M in 5.058004s
slices 1.812M (± 9.4%) i/s - 9.033M in 5.033413s
endless first slices 1.620M (± 2.4%) i/s - 8.197M in 5.061826s
endless slices 1.679M (± 3.0%) i/s - 8.490M in 5.060451s
Comparison:
slices: 1812214.4 i/s
endless slices: 1679289.2 i/s - same-ish: difference falls within error
endless first slices: 1620389.7 i/s - same-ish: difference falls within error
proc: 485481.5 i/s - 3.73x slower
then: 466964.2 i/s - 3.88x slower
transpose: 430107.5 i/s - 4.21x slower
reduce: 61227.8 i/s - 29.60x slower
Calculating -------------------------------------
transpose 511.189k (± 4.8%) i/s - 2.568M in 5.036421s
proc 737.483k (±10.0%) i/s - 3.678M in 5.046783s
reduce 79.450k (± 6.2%) i/s - 396.312k in 5.009035s
yield_self 747.791k (± 5.3%) i/s - 3.746M in 5.024160s
slices 3.796M (± 8.8%) i/s - 18.796M in 4.997241s
Comparison:
slices: 3796325.8 i/s
yield_self: 747790.9 i/s - 5.08x slower
proc: 737483.2 i/s - 5.15x slower
transpose: 511189.2 i/s - 7.43x slower
reduce: 79450.0 i/s - 47.78x slower
Calculating -------------------------------------
transpose 378.467k (±45.3%) i/s - 701.387k in 5.049225s
proc 278.442k (±22.8%) i/s - 555.768k in 5.202504s
reduce 93.156k (±30.7%) i/s - 127.890k in 5.043050s
then 58.353k (±74.0%) i/s - 65.100k in 5.014233s
slices 899.148k (±24.6%) i/s - 1.298M in 4.996822s
Comparison:
slices: 899148.2 i/s
transpose: 378466.7 i/s - 2.38x slower
proc: 278441.5 i/s - 3.23x slower
reduce: 93156.2 i/s - 9.65x slower
then: 58352.6 i/s - 15.41x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment