Skip to content

Instantly share code, notes, and snippets.

@lucaong
Created April 1, 2015 12:05
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 lucaong/ec70d8059adb48e4ca8a to your computer and use it in GitHub Desktop.
Save lucaong/ec70d8059adb48e4ca8a to your computer and use it in GitHub Desktop.
Benchmark optimization on Rack::Builder
require 'rack'
require 'benchmark'
class OptimizedRackBuilder < Rack::Builder
def call(env)
@to_app ||= to_app
@to_app.call(env)
end
end
def stub_middleware
Class.new do
def initialize(app)
@app = app
end
def call(env)
@app.call(env)
[200, {}, ['xxx']]
end
end
end
def stub_app
Proc.new do |env|
[200, {}, ['hello']]
end
end
def define_routes(klass)
klass.new do
map '/foo' do
use stub_middleware
run stub_app
end
map '/bar' do
use stub_middleware
run stub_app
end
map '/baz' do
use stub_middleware
run stub_app
end
end
end
original_app = define_routes(Rack::Builder)
optimized_app = define_routes(OptimizedRackBuilder)
env = {
"REQUEST_METHOD" => "GET",
"REQUEST_PATH" => '/bar',
"PATH_INFO" => '/bar',
"SCRIPT_NAME" => '',
"SERVER_NAME" => 'localhost',
"SERVER_PORT" => '80',
"REQUEST_URI" => 'http://localhost/bar',
"HTTP_HOST" => 'localhost'
}
n = 50_000
Benchmark.bm do |x|
x.report('original') { n.times do; original_app.call(env); end }
x.report('optimized') { n.times do; optimized_app.call(env); end }
end
# Results on my machine:
# user system total real
# original 5.930000 0.040000 5.970000 ( 5.986689)
# optimized 0.390000 0.000000 0.390000 ( 0.390511)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment