Skip to content

Instantly share code, notes, and snippets.

@thinkerbot
Created May 15, 2009 14:57
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 thinkerbot/112241 to your computer and use it in GitHub Desktop.
Save thinkerbot/112241 to your computer and use it in GitHub Desktop.
rack utils optimizations
require 'benchmark'
require 'rack'
include Rack::Utils
# This illustrates the little optimizations to Rack::Utils that you might
# consider. The parse_query optimization prevents the regeneration of the
# default separator regexp:
#
# /[#{d}] */n
#
# While the build_query optimization works because:
#
# "#{a}=#{b}"
#
# is apparently faster than:
#
# a + "=" + b
#
# Of course benchmarks can lie, but I thought you might be interested.
#
# - Simon
#
#
#
# == commit d221938a6401d956ac6cfdc892f9b1c11b1fa31a (original)
#
# % ruby -Ilib test/benchmark/rack_utils_benchmark.rb
# user system total real
# 20k x parse_query (a) 0.990000 0.000000 0.990000 ( 1.000777)
# 20k x parse_query (b) 1.010000 0.010000 1.020000 ( 1.021451)
# 30k x build_query 1.000000 0.000000 1.000000 ( 1.006995)
#
# == commit 9e4a325ff2e39e056918d32cf2216fb902cb675d (optimized)
#
# ruby -Ilib test/benchmark/rack_utils_benchmark.rb
# user system total real
# 20k x parse_query (a) 0.870000 0.000000 0.870000 ( 0.880443)
# 20k x parse_query (b) 0.890000 0.010000 0.900000 ( 0.903522)
# 30k x build_query 0.960000 0.000000 0.960000 ( 0.969581)
#
# ~ 10% speedup for parse_query
# ~ 4% speedup for build_query
#
Benchmark.bm(25) do |x|
str = "foo=bar&foo=quux&foo=baz&foo=quud&a=b"
x.report("20k x parse_query (a)") do
20000.times do
parse_query(str)
end
end
str = "my+weird+field=q1%212%22%27w%245%267%2Fz8%29%3F"
x.report("20k x parse_query (b)") do
20000.times do
parse_query(str)
end
end
query = {"foo" => "1", "bar" => "2", "baz" => "3", "quux" => "4"}
x.report("30k x build_query") do
30000.times do
build_query(query)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment