Skip to content

Instantly share code, notes, and snippets.

@jvns
Created September 17, 2016 13:00
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 jvns/69346732f69b1e02a58f72c9ff5d7411 to your computer and use it in GitHub Desktop.
Save jvns/69346732f69b1e02a58f72c9ff5d7411 to your computer and use it in GitHub Desktop.
require 'pathname'
SEPARATOR_PAT = Pathname::SEPARATOR_PAT
def chop_basename(path)
base = File.basename(path)
if /\A#{SEPARATOR_PAT}?\z/ =~ base
return nil
else
return path[0, path.rindex(base)], base
end
end
RE = Regexp.new("/\A#{SEPARATOR_PAT}?\z/")
def chop_basename2(path)
base = File.basename(path)
if RE =~ base
return nil
else
return path[0, path.rindex(base)], base
end
end
TIMES=100000
start = Time.now
TIMES.times do
chop_basename('aewsome_file.rb')
end
puts Time.now - start
start = Time.now
start = Time.now
TIMES.times do
chop_basename2('aewsome_file.rb')
end
puts Time.now - start
start = Time.now
@hborders
Copy link

RE shouldn't have / at the beginning and end.

$ ruby -e 'SEPARATOR_PATH="/"; RE=/\A#{SEPARATOR_PATH}?\z/; puts "#{RE}"'
(?-mix:\A\/?\z)
$ ruby -e 'SEPARATOR_PATH="/"; RE=Regexp.new("/\A#{SEPARATOR_PATH}?\z/"); puts "#{RE}"'
(?-mix:\/A\/?z\/)

I don't know if that will impact your benchmarks necessarily, but you definitely aren't measuring the same thing. :(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment