Skip to content

@pixeltrix /optimized_routes.rb
Last active

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Benchmark of changing optimized route generation to pre-splitting the route versus using gsub with a simple route
require 'benchmark/ips'
require 'action_controller/railtie'
ROUTE = '/posts/:id'
PARTS = [:id]
OPTIMIZED = ["/", "posts", "/", :id]
SEPARATOR = '/'
KLASS = ActionDispatch::Journey::Router::Utils
def optimized_helper_1(*args)
path = ROUTE.dup
klass = ActionDispatch::Journey::Router::Utils
PARTS.zip(args) do |part, arg|
parameterized_arg = arg.to_param
if parameterized_arg.nil? || parameterized_arg.empty?
raise ActionController::UrlGenerationError
end
path.gsub!(/(\*|:)#{part}/, klass.escape_fragment(parameterized_arg))
end
path
end
def optimized_helper_2(*args)
params = Hash[parameterize_args(args)]
missing = missing_keys(params)
unless missing.empty?
raise ActionController::UrlGenerationError
end
OPTIMIZED.map{ |segment| replace_segment(params, segment) }.join
end
def replace_segment(params, segment)
Symbol === segment ? KLASS.escape_fragment(params[segment]) : segment
end
def parameterize_args(args)
[].tap do |parameterized_args|
PARTS.zip(args) do |part, arg|
parameterized_arg = arg.to_param
parameterized_args << [part, parameterized_arg]
end
end
end
def missing_keys(args)
args.select{ |part, arg| arg.nil? || arg.empty? }.keys
end
Benchmark.ips do |x|
x.report('Current Helper: ') { optimized_helper_1(1) }
x.report('New Helper: ') { optimized_helper_2(1) }
end
Calculating -------------------------------------
Current Helper: 5274 i/100ms
New Helper: 8050 i/100ms
-------------------------------------------------
Current Helper: 79263.6 (±3.7%) i/s - 395550 in 4.997252s
New Helper: 153464.5 (±4.9%) i/s - 772800 in 5.047834s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.