Created
September 3, 2014 15:01
-
-
Save unleashed/1e4bc6b3dbaebe7ab6df to your computer and use it in GitHub Desktop.
mikz: does anyway have better way of converting whatever/string/like/this to [['whatever'], ['whatever', 'string'], ['whatever', 'string', 'like'], ['whatever', 'string', 'like', 'this']] than: str.split('/').reduce([]){ |acc, v| acc.push(([acc.last].compact + [v]).flatten) }
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
require 'benchmark' | |
loops = 1_000_000 | |
str = 'whatever/string/like/this' | |
Benchmark.bm do |x| | |
x.report 'michal1' do | |
loops.times do | |
str.split('/').reduce([]){ |acc, v| acc.push(([acc.last].compact + [v]).flatten) } | |
end | |
end | |
x.report 'rgrau1' do | |
loops.times do | |
acc = [[]]; str.split('/').map { |elem| acc << (acc[-1] + [elem]).flatten }; acc | |
end | |
end | |
x.report 'alex1' do | |
loops.times do | |
str.split('/').inject([]) { |acc, v| acc << ((acc.last || []) + [v]) } | |
end | |
end | |
x.report 'michal2' do | |
loops.times do | |
str.split('/').reduce([[]]){ |acc, v| acc.push(acc.last.push(v).dup) }.uniq | |
end | |
end | |
x.report 'alex2' do | |
loops.times do | |
[].tap { |w| a=str.split('/'); a.size.times { |i| w << a[0..i] } } | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
alex@inxs:~/dev/3scale/core$ ruby bm.rb
user system total real
michal1 7.160000 0.000000 7.160000 ( 7.165719)
rgrau1 5.910000 0.000000 5.910000 ( 5.901147)
alex1 2.910000 0.000000 2.910000 ( 2.909804)
michal2 14.310000 0.000000 14.310000 ( 14.305894)
alex2 2.820000 0.000000 2.820000 ( 2.819322)