Last active
August 10, 2016 08:12
-
-
Save jodosha/d457b44ee60744b754a843b7d3f8d54f to your computer and use it in GitHub Desktop.
Hanami::Action::Params#error_messages: each_with_object vs flat_map benchmark
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env ruby | |
| require 'bundler/setup' | |
| require 'benchmark/ips' | |
| require 'hanami/controller' | |
| class Hanami::Action::Params | |
| def flat_map_error_messages(error_set = errors) | |
| error_set.flat_map do |key, messages| | |
| k = Hanami::Utils::String.new(key).titleize | |
| if messages.is_a?(Hash) | |
| flat_map_error_messages(messages) | |
| else | |
| messages.map! { |message| "#{k} #{message}" } | |
| end | |
| end | |
| end | |
| end | |
| class TestParams < Hanami::Action::Params | |
| params do | |
| required(:email).filled(format?: /\A.+@.+\z/) | |
| required(:name).filled | |
| required(:tos).filled(:bool?) | |
| required(:age).filled(:int?) | |
| required(:address).schema do | |
| required(:line_one).filled | |
| required(:deep).schema do | |
| required(:deep_attr).filled(:str?) | |
| end | |
| end | |
| end | |
| end | |
| params = TestParams.new({}) | |
| Benchmark.ips do |x| | |
| x.report('each_with_object') { params.error_messages } | |
| x.report('flat_map') { params.flat_map_error_messages } | |
| x.compare! | |
| end | |
| __END__ | |
| Result: | |
| Warming up -------------------------------------- | |
| each_with_object 465.000 i/100ms | |
| flat_map 450.000 i/100ms | |
| Calculating ------------------------------------- | |
| each_with_object 4.598k (± 6.2%) i/s - 23.250k in 5.079603s | |
| flat_map 4.602k (± 4.1%) i/s - 23.400k in 5.093111s | |
| Comparison: | |
| flat_map: 4602.1 i/s | |
| each_with_object: 4597.7 i/s - same-ish: difference falls within error | |
| Ruby: | |
| ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15] | |
| Hardware: | |
| Hardware Overview: | |
| Model Name: MacBook Pro | |
| Model Identifier: MacBookPro12,1 | |
| Processor Name: Intel Core i7 | |
| Processor Speed: 3.1 GHz | |
| Number of Processors: 1 | |
| Total Number of Cores: 2 | |
| L2 Cache (per Core): 256 KB | |
| L3 Cache: 4 MB | |
| Memory: 16 GB | |
| Boot ROM Version: MBP121.0167.B16 | |
| SMC Version (system): 2.28f7 | |
| Software: | |
| System Software Overview: | |
| System Version: OS X 10.11.5 (15F34) | |
| Kernel Version: Darwin 15.5.0 | |
| Time since boot: 2 days 1:00 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment