Skip to content

Instantly share code, notes, and snippets.

@nolan
Last active December 12, 2015 06:48
Show Gist options
  • Save nolan/4731578 to your computer and use it in GitHub Desktop.
Save nolan/4731578 to your computer and use it in GitHub Desktop.
Benchmark flatten vs manual array creation
require "benchmark"
n = 50000
a = ('A'..'Z').to_a
a = a.zip(a) # [["A", "A"], ["B", "B"], ["C", "C"]...]
Benchmark.bm(7) do |x|
x.report("manual:") { n.times do; a.map {|b| ['X', b[0], b[1]] }; end }
x.report("flatten:") { n.times do; a.map {|b| ['X', b].flatten }; end }
end
@bradland
Copy link

bradland commented Feb 7, 2013

Under: ruby 1.9.3p125 (2012-02-16 revision 34643) [x86_64-darwin12.0.0]

              user     system      total        real
manual:   0.410000   0.010000   0.420000 (  0.475863)
flatten:  1.850000   0.020000   1.870000 (  1.900730)

@bradland
Copy link

bradland commented Feb 7, 2013

Under: ruby 1.9.3p327 (2012-11-10) [x86_64-darwin12.2.0]

              user     system      total        real
manual:   0.980000   0.020000   1.000000 (  1.112109)
flatten:  3.860000   0.050000   3.910000 (  4.010452)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment