Skip to content

Instantly share code, notes, and snippets.

@tessi
Last active December 24, 2015 09:49
Show Gist options
  • Save tessi/6779700 to your computer and use it in GitHub Desktop.
Save tessi/6779700 to your computer and use it in GitHub Desktop.
require 'benchmark'
iterations = 10_000
arr = Array.new(1000) { Array.new(2) << (rand()*100).to_s}
def use_map_join(arr)
arr.map {|a| a[2]}.join ', '
end
def use_inject(arr)
join_str = ', '
arr.inject(nil) {|str, arr| str ? (str << join_str << arr[2]) : arr[2].dup}
end
Benchmark.bm do |bm|
bm.report('map/join') do
iterations.times do
use_map_join arr
end
end
bm.report('inject') do
iterations.times do
use_inject arr
end
end
end
user system total real
map/join 1.440000 0.000000 1.440000 ( 1.441858)
inject 2.220000 0.000000 2.220000 ( 2.234554)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment