Skip to content

Instantly share code, notes, and snippets.

@phstc
Last active December 20, 2015 03:18
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 phstc/6062246 to your computer and use it in GitHub Desktop.
Save phstc/6062246 to your computer and use it in GitHub Desktop.
require 'benchmark'
# $ ruby -v
# => ruby 1.9.3p392 (2013-02-22 revision 39386) [x86_64-darwin12.2.0]
#
# N.times { |i| RINDEX.deconstantize(A::B::C::D.name) }
# user system total real
# rindex 0.160000 0.000000 0.160000 ( 0.164055)
# gsub 0.580000 0.010000 0.590000 ( 0.683018)
#
# N.times { |i| RINDEX.deconstantize(D.name) }
# user system total real
# rindex 0.160000 0.000000 0.160000 ( 0.175646)
# gsub 0.160000 0.000000 0.160000 ( 0.201934)
#
# N.times { |i| RINDEX.demodulize(A::B::C::D.name) }
# user system total real
# rindex 0.160000 0.000000 0.160000 ( 0.189615)
# gsub 0.590000 0.010000 0.600000 ( 0.740444)
#
# N.times { |i| RINDEX.demodulize(D.name) }
# user system total real
# rindex 0.090000 0.000000 0.090000 ( 0.099179)
# gsub 0.160000 0.000000 0.160000 ( 0.184077)
module RINDEX
def self.demodulize(path)
path = path.to_s
if i = path.rindex('::')
path[(i+2)..-1]
else
path
end
end
def self.deconstantize(path)
path.to_s[0...(path.rindex('::') || 0)] # implementation based on the one in facets' Module#spacename
end
end
module GSUB
def self.demodulize(path)
path.to_s.gsub(/^.*::/, '')
end
def self.deconstantize(path)
path.to_s.gsub(/::.*/, '')
end
end
N = 100000
module A
module B
module C
class D; end
end
end
end
class D; end
puts " N.times { |i| RINDEX.deconstantize(A::B::C::D.name) }\n"
Benchmark.bm(13) do |x|
x.report("rindex") {
N.times { |i| RINDEX.deconstantize(A::B::C::D.name) }
}
x.report("gsub") {
N.times { |i| GSUB.deconstantize(A::B::C::D.name) }
}
end
puts " N.times { |i| RINDEX.deconstantize(D.name) }\n"
Benchmark.bm(13) do |x|
x.report("rindex") {
N.times { |i| RINDEX.deconstantize(D.name) }
}
x.report("gsub") {
N.times { |i| GSUB.deconstantize(D.name) }
}
end
puts " N.times { |i| RINDEX.demodulize(A::B::C::D.name) }\n"
Benchmark.bm(13) do |x|
x.report("rindex") {
N.times { |i| RINDEX.demodulize(A::B::C::D.name) }
}
x.report("gsub") {
N.times { |i| GSUB.demodulize(A::B::C::D.name) }
}
end
puts " N.times { |i| RINDEX.demodulize(D.name) }\n"
Benchmark.bm(13) do |x|
x.report("rindex") {
N.times { |i| RINDEX.demodulize(D.name) }
}
x.report("gsub") {
N.times { |i| GSUB.demodulize(D.name) }
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment