Last active
December 24, 2015 09:49
-
-
Save tessi/6779700 to your computer and use it in GitHub Desktop.
benchmark for this SO question: http://stackoverflow.com/questions/19118688/ruby-array-map-and-join-in-one-loop
This file contains 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' | |
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 |
This file contains 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
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