Skip to content

Instantly share code, notes, and snippets.

@svenfuchs
Created September 18, 2008 10:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svenfuchs/11417 to your computer and use it in GitHub Desktop.
Save svenfuchs/11417 to your computer and use it in GitHub Desktop.
# see http://pastie.org/274816 and http://pastie.org/274829
# I have: "foo"
# I need: ['f', 'fo', 'foo']
require 'benchmark'
def using_split(str)
str.split(//mu).inject([]) do |arr, char|
arr << arr[-1].to_s + char.to_s
end
end
def using_map(str)
(1..str.length).map do |i|
str[0, i]
end
end
def using_upto(str)
result = []
1.upto(str.length) do |i|
result << str[0, i]
end
result
end
def using_times(str)
result = []
i = 1
str.length.times do
result << str[0, i]
i += 1
end
result
end
def using_for(str)
result = []
for i in 1..str.length
result << str[0, i]
end
result
end
puts "using_split: " + using_split("foo").inspect
puts "using_map: " + using_map("foo").inspect
puts "using_upto: " + using_upto("foo").inspect
puts "using_times: " + using_times("foo").inspect
puts "using_for: " + using_for("foo").inspect
Benchmark.bm(100000) do |x|
x.report { using_split("foo") }
x.report { using_map("foo") }
x.report { using_upto("foo") }
x.report { using_times("foo") }
x.report { using_for("foo") }
end
using_split: ["f", "fo", "foo"]
using_map: ["f", "fo", "foo"]
using_upto: ["f", "fo", "foo"]
using_times: ["f", "fo", "foo"]
using_for: ["f", "fo", "foo"]
user system total real
0.000000 0.000000 0.000000 ( 0.000033)
0.000000 0.000000 0.000000 ( 0.000031)
0.000000 0.000000 0.000000 ( 0.000019)
0.000000 0.000000 0.000000 ( 0.000021)
0.000000 0.000000 0.000000 ( 0.000029)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment