Last active
January 2, 2016 06:09
-
-
Save pixeltrix/8261932 to your computer and use it in GitHub Desktop.
Benchmark of changing optimized route generation to pre-splitting the route versus using gsub with a simple route
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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