hanami / api

Minimal, lightweight, fastest Ruby framework for HTTP APIs.
https://hanamirb.org
MIT License
350 stars 13 forks source link

Simplify Hanami::Api::Block::Context#call #14

Closed DNNX closed 4 years ago

DNNX commented 4 years ago

With more extensive use of as-patterns, the Hanami::Api::Block::Context#call method can be simplified to such an extent that one AbcSize RuboCop violation does not longer exist and the rubocop:disable directive can be dropped.

Performance-wise, old and new styles of pattern matching are very similar. Benchmpark/ips reports that the difference between them "falls within error".

This is the microbenchmark code I used:

# frozen_string_literal: true

require 'benchmark/ips'

def call1(caught)
  case caught
  in [Integer, Hash, String] => response
  @h = response[1]
  @s = response[0]
  @b = response[2]
  end
end

def call2(caught)
  case caught
  in [Integer => status, Hash => h, String => body]
  @h = h
  @s = status
  @b = body
  end
end

caught = [200, {}, 'body']

Benchmark.ips do |x|
  x.report('original') { call1(caught) }
  x.report('new') { call2(caught) }
  x.compare!
end

__END__

Warming up --------------------------------------
            original   288.026k i/100ms
                 new   288.478k i/100ms
Calculating -------------------------------------
            original      2.884M (± 2.0%) i/s -     14.689M in   5.096077s
                 new      2.923M (± 1.3%) i/s -     14.712M in   5.033728s

Comparison:
                 new:  2923260.2 i/s
            original:  2883644.7 i/s - same-ish: difference falls within error

On a bigger scale, the difference is going to be even less noticeable.