Skip to content
  • Ricardo Díaz's avatar
    93cbc30f
    Use Enumerator#all? and Enumerator#any? with classes instead of iterations · 93cbc30f
    Ricardo Díaz authored
    These methods have changed in Ruby 2.5 to be more akin to grep:
    
    https://bugs.ruby-lang.org/issues/11286
    
    Using classes seems to be faster (and a bit more expressive) than iterating over
    the collection items:
    
    ```
    Warming up --------------------------------------
        #all? with class   504.000  i/100ms
         #all? with proc   189.000  i/100ms
    Calculating -------------------------------------
        #all? with class      4.960k (± 1.6%) i/s -     25.200k in   5.082049s
         #all? with proc      1.874k (± 2.8%) i/s -      9.450k in   5.047866s
    
    Comparison:
        #all? with class:     4959.9 i/s
         #all? with proc:     1873.8 i/s - 2.65x  (± 0.00) slower
    ```
    
    Benchmark script:
    
    ```ruby
    require "minitest/autorun"
    require "benchmark/ips"
    
    class BugTest < Minitest::Test
      def test_enumerators_with_classes
        arr = (1..10000).to_a << nil
    
        assert_equal arr.all?(Integer), arr.all? { |v| v.is_a?(Integer) }
    
        Benchmark.ips do |x|
          x.report("#all? with class") do
            arr.all?(Integer)
          end
    
          x.report("#all? with proc") do
            arr.all? { |v| v.is_a?(Integer) }
          end
    
          x.compare!
        end
      end
    end
    ```
    93cbc30f
    Use Enumerator#all? and Enumerator#any? with classes instead of iterations
    Ricardo Díaz authored
    These methods have changed in Ruby 2.5 to be more akin to grep:
    
    https://bugs.ruby-lang.org/issues/11286
    
    Using classes seems to be faster (and a bit more expressive) than iterating over
    the collection items:
    
    ```
    Warming up --------------------------------------
        #all? with class   504.000  i/100ms
         #all? with proc   189.000  i/100ms
    Calculating -------------------------------------
        #all? with class      4.960k (± 1.6%) i/s -     25.200k in   5.082049s
         #all? with proc      1.874k (± 2.8%) i/s -      9.450k in   5.047866s
    
    Comparison:
        #all? with class:     4959.9 i/s
         #all? with proc:     1873.8 i/s - 2.65x  (± 0.00) slower
    ```
    
    Benchmark script:
    
    ```ruby
    require "minitest/autorun"
    require "benchmark/ips"
    
    class BugTest < Minitest::Test
      def test_enumerators_with_classes
        arr = (1..10000).to_a << nil
    
        assert_equal arr.all?(Integer), arr.all? { |v| v.is_a?(Integer) }
    
        Benchmark.ips do |x|
          x.report("#all? with class") do
            arr.all?(Integer)
          end
    
          x.report("#all? with proc") do
            arr.all? { |v| v.is_a?(Integer) }
          end
    
          x.compare!
        end
      end
    end
    ```
Loading