-
-
Save havenwood/a69ac7262062a20c7c24efc5950d9614 to your computer and use it in GitHub Desktop.
This file contains 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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ruby 2.5.1; Intel(R) Core(TM) i7-3520M CPU @ 2.90GHz