Skip to content

Instantly share code, notes, and snippets.

@havenwood
Forked from radar/playground.rb
Last active September 19, 2018 02:37
Show Gist options
  • Save havenwood/a69ac7262062a20c7c24efc5950d9614 to your computer and use it in GitHub Desktop.
Save havenwood/a69ac7262062a20c7c24efc5950d9614 to your computer and use it in GitHub Desktop.
class Question
end
class Answer
attr_reader :question, :score
def initialize(question, score)
@question = question
@score = score
end
end
module AnswerScoreHelpers
refine Answer do
def low?
score < 3
end
def neutral?
score == 3
end
def high?
score > 3
end
end
end
class Response
using AnswerScoreHelpers
attr_reader :answers
def initialize(answers = [])
@answers = answers
end
def low_answers_for_question(question)
answers.select(&for_question(question)).select(&:low?)
end
def low_answers_for_question_one_iteration(question)
answers.select do |answer|
for_question(question) && answer.low?
end
end
def for_question(question)
->(answer) { answer.question == question }
end
end
require 'benchmark/ips'
[5, 1_000, 100_000].each do |n|
question = Question.new
answers = n.times.map { Answer.new question, rand(1..5) }
response = Response.new(answers)
Benchmark.ips do |x|
x.report("#{n} chained") { response.low_answers_for_question(question) }
x.report("#{n} single") { response.low_answers_for_question_one_iteration(question) }
x.compare!
end
end
@gr33n7007h
Copy link

Ruby 2.5.1; Intel(R) Core(TM) i7-3520M CPU @ 2.90GHz

           5 chained    36.739k i/100ms
            5 single    33.191k i/100ms
Calculating -------------------------------------
           5 chained    473.473k (±19.4%) i/s -      2.278M in   5.012645s
            5 single    411.905k (±20.0%) i/s -      1.991M in   5.038688s

Comparison:
           5 chained:   473472.6 i/s
            5 single:   411905.1 i/s - same-ish: difference falls within error

Warming up --------------------------------------
        1000 chained   437.000  i/100ms
         1000 single   219.000  i/100ms
Calculating -------------------------------------
        1000 chained      4.718k (±15.8%) i/s -     23.161k in   5.069779s
         1000 single      2.570k (±15.5%) i/s -     12.702k in   5.066283s

Comparison:
        1000 chained:     4718.3 i/s
         1000 single:     2570.1 i/s - 1.84x  slower

Warming up --------------------------------------
      100000 chained     4.000  i/100ms
       100000 single     2.000  i/100ms
Calculating -------------------------------------
      100000 chained     44.157  (±15.9%) i/s -    216.000  in   5.026789s
       100000 single     25.488  (±15.7%) i/s -    126.000  in   5.043198s

Comparison:
      100000 chained:       44.2 i/s
       100000 single:       25.5 i/s - 1.73x  slower

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment