Guest User

if+include VS case+expand benchmark

a guest
Jul 22nd, 2021
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.01 KB | None | 0 0
  1. require "benchmark/ips"
  2.  
  3. FIRST_CASE = ["house", "home", "building"]
  4. SECOND_CASE = ["boat", "vessel", "ship"]
  5. ARGUMENT = "vessel"
  6.  
  7. def if_include_test
  8.   if FIRST_CASE.include?(ARGUMENT)
  9.     :first
  10.   elsif SECOND_CASE.include?(ARGUMENT)
  11.     :second
  12.   else
  13.     nil
  14.   end
  15. end
  16.  
  17. def case_expand_test
  18.   case ARGUMENT
  19.   when *FIRST_CASE then :first
  20.   when *SECOND_CASE then :second
  21.   else
  22.     nil
  23.   end
  24. end
  25.  
  26. Benchmark.ips do |x|
  27.   x.report("if + include?") { if_include_test }
  28.   x.report("case + expand") { case_expand_test }
  29.   x.compare!
  30. end
  31.  
  32. =begin
  33. Warming up --------------------------------------
  34.        if + include?   544.249k i/100ms
  35.        case + expand   335.889k i/100ms
  36. Calculating -------------------------------------
  37.        if + include?      5.255M (± 9.5%) i/s -     26.124M in   5.022296s
  38.        case + expand      3.389M (± 8.3%) i/s -     17.130M in   5.089028s
  39.  
  40. Comparison:
  41.        if + include?:  5254775.2 i/s
  42.        case + expand:  3388705.3 i/s - 1.55x  (± 0.00) slower
  43. =end
  44.  
Advertisement
Add Comment
Please, Sign In to add comment