Two not mentioned earlier and faster than in @ toro2k accepted the comparison.
(1..s.size).map { |i| s[0, i] } => ["r", "ru", "rub", "ruby"] Array.new(s.size) { |i| s[0, i+1] } => ["r", "ru", "rub", "ruby"]
Strange, no one used String#[start, length] before, only slower than String#[range] .
And I think that at least my first decision is pretty simple.
Test results (using Ruby 2.4.2):
user system total real toro2k 14.594000 0.000000 14.594000 ( 14.724630) marek_lipka 12.485000 0.000000 12.485000 ( 12.635404) jorg_w_mittag 16.968000 0.000000 16.968000 ( 17.080315) jorg_w_mittag_2 11.828000 0.000000 11.828000 ( 11.935078) stefan 10.766000 0.000000 10.766000 ( 10.831517) stefanpochmann 9.734000 0.000000 9.734000 ( 9.765227) stefanpochmann 2 8.219000 0.000000 8.219000 ( 8.240854)
My control code:
require 'benchmark' string = 'ruby' @n = 10**7 Benchmark.bm(20) do |x| @x = x def report(name, &block) @x.report(name) { @n.times(&block) } end report('toro2k') { string.size.times.collect { |i| string[0..i] } } report('marek_lipka') { (0...(string.length)).map{ |i| string[0..i] } } report('jorg_w_mittag') { string.chars.inject([[], '']) { |(res, memo), c| [res << memo += c, memo] }.first } report('jorg_w_mittag_2') { acc = '' string.chars.map {|c| acc += c } } report('stefan') { Array.new(string.size) { |i| string[0..i] } } report('stefanpochmann') { (1..string.size).map { |i| string[0, i] } } report('stefanpochmann 2') { Array.new(string.size) { |i| string[0, i+1] } } end
source share