Skip to content

Instantly share code, notes, and snippets.

@RobertDober
Created June 29, 2010 20:19
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 RobertDober/457751 to your computer and use it in GitHub Desktop.
Save RobertDober/457751 to your computer and use it in GitHub Desktop.
require 'benchmark'
TIMES = 4_000
s = "you like to play with your yo-yo" * 100
Count = 400
def check!
abort "count not #{Count} but #{@count}" unless @count == Count
end
Benchmark.bmbm do |x|
x.report("scan") do
TIMES.times do
@count = s.scan("yo").size
end
check!
end
x.report("scan ++") do
TIMES.times do
@count = 0
s.scan("yo") { @count += 1 }
end
check!
end
x.report("scan re") do
TIMES.times do
@count = s.scan(/yo/).size
end
check!
end
x.report("scan re ++") do
TIMES.times do
@count = 0
s.scan(/yo/) { @count += 1 }
end
check!
end
x.report "gsub" do
TIMES.times do
@count = s.size - s.gsub("yo","").size
@count /= "yo".size
end
check!
end
x.report("while") do
TIMES.times do
len = "yo".length
index = -len
@count = 0
while index = s.index("yo", index + len)
@count += 1
end
end
check!
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment