Created
December 20, 2016 13:10
-
-
Save jessiel-hacke/c608dd55fa76d56650fa13c5a17fe2b2 to your computer and use it in GitHub Desktop.
Benchmark flatten alternatives
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
# methods defined on main:Object | |
def iron(array) | |
a = [] | |
array.each do |element| | |
if element.is_a? Array | |
a.push(*iron(element)) | |
else | |
a.append(element) | |
end | |
end | |
a | |
end | |
def implode(array) | |
array.each_with_object([]) do |element, flat| | |
flat.push(*(element.is_a?(Array) ? implode(element) : element)) | |
end | |
end | |
def stomp(array) | |
array.inject([]) { |a, element| a + Array(element.is_a?(Array) ? element.stomp : element) } | |
end | |
# In class methods | |
class Array | |
def implode | |
each_with_object([]) do |element, flat| | |
flat.push(*(element.is_a?(Array) ? element.implode : element)) | |
end | |
end | |
def iron | |
a = [] | |
each do |element| | |
if element.is_a? Array | |
a.push(*element.iron) | |
else | |
a.append(element) | |
end | |
end | |
a | |
end | |
def stomp | |
inject([]) { |a, element| a + Array(element.is_a?(Array) ? element.stomp : element) } | |
end | |
end | |
# Benchmark comparing all the above with Array#flatten | |
def run_bm(n=50_000, a=[[9, 8, 7, 4], 1, 6, 4, [9, 4, 2]]) | |
Benchmark.bm do |bm| | |
bm.report('Array#implode') { n.times { a.implode } } | |
bm.report('main:Object#implode') { n.times { implode(a) } } | |
bm.report('Array#iron') { n.times { a.iron } } | |
bm.report('main:Object#iron') { n.times { iron(a) } } | |
bm.report('Array#stomp') { n.times { a.stomp } } | |
bm.report('main:Object#stomp') { n.times { stomp(a) } } | |
bm.report('Array#flatten') { n.times { a.flatten } } | |
end | |
end | |
# Benchmark Results | |
user system total real | |
Array#implode 0.360000 0.000000 0.360000 ( 0.368209) | |
main:Object#implode 0.290000 0.000000 0.290000 ( 0.287446) | |
Array#iron 0.150000 0.000000 0.150000 ( 0.149134) | |
main:Object#iron 0.140000 0.000000 0.140000 ( 0.144023) | |
Array#stomp 0.430000 0.000000 0.430000 ( 0.425000) | |
main:Object#stomp 0.410000 0.000000 0.410000 ( 0.408995) | |
Array#flatten 0.110000 0.000000 0.110000 ( 0.108783) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment