Skip to content

Instantly share code, notes, and snippets.

@bradland
Last active August 29, 2015 14:12
Show Gist options
  • Save bradland/96e05f5c09d61acc82fc to your computer and use it in GitHub Desktop.
Save bradland/96e05f5c09d61acc82fc to your computer and use it in GitHub Desktop.
String replacement/removal method benchmarks.
require 'benchmark'
alias e puts
N = "\n"
N_TIMES = 550_000 # Run it n times.
e 'We will next compare the elimination of the character "f"'
e 'by comparing the methods .delete .gsub and .tr'+N+N
# Our Test String comes next.
TEST_STRING = ('abc def ghi jkl '+N) * 80
Benchmark.bm(17) { |x|
x.report('Testing: .tr') {
N_TIMES.times { TEST_STRING.tr('f','') }
}
x.report('Testing: .gsub') {
N_TIMES.times { TEST_STRING.gsub('f','') }
}
x.report('Testing: .delete') {
N_TIMES.times { TEST_STRING.delete('f') }
}
}
require 'benchmark/ips'
Benchmark.ips do |x|
# These parameters can also be configured this way
x.time = 5
x.warmup = 2
TEST_STRING = ('abc def ghi jkl \n') * 80
x.report('Testing: .tr') { TEST_STRING.tr('f','') }
x.report('Testing: .gsub') { TEST_STRING.gsub('f','') }
x.report('Testing: .delete') { TEST_STRING.delete('f') }
x.compare!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment