Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prefer Hash#[] over Set#.include? for speed #312

Merged
merged 1 commit into from Jun 17, 2016

Commits on Jun 15, 2016

  1. Prefer Hash#[] over Set#.include? for speed

    Playing with stackprof against codetriage and for an initial run with no cache `Set#include?` was the top called method, something around 8% of execution time spent there.
    
    Did a microbenchmark to see if it would be faster to use a hash:
    
    ```
    require 'benchmark/ips'
    
    require 'set'
    
    set  = Set.new [:foo, :bar]
    hash = {foo: true, bar: true}
    
    Benchmark.ips do |x|
      x.report("set ") {|num|
        i = 0
        while i < num
          set.include?(:foo)
          i += 1
        end
    
      }
      x.report("hash") {|num|
        i = 0
        while i < num
          hash[:foo]
          i += 1
        end
      }
      x.compare!
    end
    
    # Warming up --------------------------------------
    #                 set    215.314k i/100ms
    #                 hash   219.939k i/100ms
    # Calculating -------------------------------------
    #                 set      11.715M (±15.5%) i/s -     56.843M in   5.010837s
    #                 hash     20.119M (±18.2%) i/s -     96.333M in   5.010977s
    
    # Comparison:
    #                 hash: 20118880.7 i/s
    #                 set : 11714839.0 i/s - 1.72x slower
    ```
    
    Yes, it is faster.
    
    Anecdotally when running `RAILS_ENV=production time rake assets:precompile` against codetriage:
    
    Before patch:
    
    ```
    eal    0m18.325s
    user    0m14.564s
    sys    0m2.729s
    ```
    
    After patch:
    
    ```
    real    0m17.981s
    user    0m14.461s
    sys    0m2.716s
    ```
    schneems committed Jun 15, 2016
    Copy the full SHA
    f032821 View commit details
    Browse the repository at this point in the history