Sha256: 55e2243012bd09b52878a4197922634355286048997ad64bc01618d12e7f226e

Contents?: true

Size: 1.52 KB

Versions: 1

Compression:

Stored size: 1.52 KB

Contents

require 'rack'
require 'pry'
require 'json'
require_relative '../lib/rack/reducer'
require 'benchmark/ips'
require_relative 'fixtures'
require 'sequel'

DB = Sequel.sqlite.tap do |db|
  db.create_table(:artists) do
    primary_key :id
    String :name
    String :genre
    Integer :release_count
  end
  Fixtures::DB[:artists].each { |row| db[:artists].insert(row) }
end

conditional_app = lambda do |env|
  params = Rack::Request.new(env).params
  @artists = DB[:artists]
  if (genre = params['genre'])
    @artists = @artists.where(genre: genre.to_s)
  end
  if (name = params['name'])
    @artists = @artists.grep(:name, "%#{name}%", case_insensitive: true)
  end
  Rack::Response.new(@artists).finish
end

TestReducer = Rack::Reducer.create(
  DB[:artists],
  ->(genre:) { where(genre: genre.to_s) },
  ->(name:) { grep(:name, "%#{name}%", case_insensitive: true) },
)

reducer_app = lambda do |env|
  params = Rack::Request.new(env).params
  @artists = TestReducer.apply(params)
  Rack::Response.new(@artists).finish
end

Benchmark.ips do |bm|
  env = {
    'REQUEST_METHOD' => 'GET',
    'PATH_INFO' => '/',
    'rack.input' => StringIO.new('')
  }

  query = {
    'QUERY_STRING' => 'name=blake&genre=electronic',
  }

  bm.report('Conditionals (full)') do
    conditional_app.call env.merge(query)
  end

  bm.report('Reducer (full)') do
    reducer_app.call env.merge(query)
  end

  bm.report('Conditionals (empty)') do
    conditional_app.call env.dup
  end

  bm.report('Reducer (empty)') do
    reducer_app.call env.dup
  end

  bm.compare!
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rack-reducer-1.1.0 spec/benchmarks.rb