Skip to content

Instantly share code, notes, and snippets.

@madwork
Created Feb 19, 2019
Embed
What would you like to do?
URI parse parameters
require 'benchmark/ips'
require 'rack/utils'
require 'uri'
require 'cgi'
uri = URI.parse "https://reedsy.com/?foo=1&bar=2"
# [2.5.3] 0:(main) > Rack::Utils.parse_nested_query uri.query
# => {
# "foo" => "1",
# "bar" => "2"
# }
# [2.5.3] 0:(main) > URI.decode_www_form(uri.query.to_s).to_h
# => {
# "foo" => "1",
# "bar" => "2"
# }
# [2.5.3] 0:(main) > CGI.parse(uri.query.to_s).transform_values(&:first)
# => {
# "foo" => "1",
# "bar" => "2"
# }
Benchmark.ips do |x|
x.report("Rack") { Rack::Utils.parse_nested_query uri.query }
x.report("URI") { URI.decode_www_form(uri.query.to_s).to_h }
x.report("CGI") { CGI.parse(uri.query.to_s).transform_values(&:first) }
end
# Warming up --------------------------------------
# Rack 8.840k i/100ms
# URI 20.736k i/100ms
# CGI 16.833k i/100ms
# Calculating -------------------------------------
# Rack 87.986k (± 3.1%) i/s - 442.000k in 5.028284s
# URI 217.241k (± 3.6%) i/s - 1.099M in 5.065639s
# CGI 175.202k (± 3.2%) i/s - 875.316k in 5.001075s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment