Skip to content

Instantly share code, notes, and snippets.

@benpickles
Last active October 15, 2019 09:54
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 benpickles/6286953 to your computer and use it in GitHub Desktop.
Save benpickles/6286953 to your computer and use it in GitHub Desktop.
When you only want to substitute one thing use `sub` instead of `gsub`.
Rehearsal ----------------------------------------
gsub 0.013451 0.000356 0.013807 ( 0.013817)
sub 0.005154 0.000086 0.005240 ( 0.005302)
------------------------------- total: 0.019047sec
user system total real
gsub 0.011792 0.000351 0.012143 ( 0.012186)
sub 0.003583 0.000001 0.003584 ( 0.003583)
# frozen_string_literal: true
require 'benchmark'
HOST_WITH_PORT = 'example.com:80'
HOW_MANY = 10_000
REGEXP = /:\d+\z/
Benchmark.bmbm do |x|
x.report('gsub') {
HOW_MANY.times do
HOST_WITH_PORT.gsub(REGEXP, '')
end
}
x.report('sub') {
HOW_MANY.times do
HOST_WITH_PORT.sub(REGEXP, '')
end
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment