Skip to content

Instantly share code, notes, and snippets.

View dominikh's full-sized avatar

Dominik Honnef dominikh

View GitHub Profile
require 'benchmark'
n = 1_000_000
s = "a b c d e f g h"
Benchmark.bmbm do |x|
x.report("Scan (regexp)") { n.times { s.scan(/h/).empty? } }
x.report("Scan (string)") { n.times { s.scan("h").empty? } }
x.report("Include") { n.times { s.include?("h") } }
x.report("=~") { n.times { s =~ /h/} }
x.report("Scan (regexp) (not findable)") { n.times { s.scan(/i/).empty? } }
require "benchmark"
def f(i); i; end
array = Array.new(1_000_000) { rand.to_s }
TESTS = 5
Benchmark.bmbm do |results|
results.report("null:") { TESTS.times { array.each { |i| f(i) } } }
results.report("sliced each:") { TESTS.times { array[1,array.size-2].each { |i| f(i) } } }
require 'benchmark'
n = 1_000_000
Benchmark.bmbm do |x|
x.report("Double quotes") do
n.times do
str = "A simple string"
end
end
x.report("Single quotes") do
require "benchmark"
n = 1_000_000
s = "a string to split"
d1 = / /
d2 = " "
Benchmark.bmbm do |x|
x.report("Regexp") do
require 'benchmark'
TIMES = 1_000_000
string = ' some weird string with spaces in it '
Benchmark.bmbm do |x|
x.report("gsub + regexp") do
TIMES.times do |t|
string.gsub(/\s+/,'-')
end
class A < Struct.new(:a, :b)
end
B = Struct.new(:a, :b)
require 'benchmark'
Benchmark.bmbm 20 do |r|
n = 10_000_000
a = A.new(1,2)
require 'benchmark'
TIMES = 1_000_000
Benchmark.bmbm() do |x|
# note: this regexp will only be built once for all iterations
x.report("literal regexp") do
TIMES.times { /regexp/ }
end
require 'benchmark'
TIMES = 1_000_000
r = /regexp/
s = "regexp"
Benchmark.bmbm do |x|
x.report("r =~ s") do
TIMES.times { r =~ s }
require 'benchmark'
TIMES = 1_000_000
s = "a string"
Benchmark.bmbm do |x|
x.report("delete") do
TIMES.times { s.delete(" ") }
end
require 'benchmark'
TIMES = 1_000_000
s = "a string"
Benchmark.bmbm do |x|
x.report("delete") do
TIMES.times { s.delete("rin") }
end