fastruby / fast-ruby

:dash: Writing Fast Ruby :heart_eyes: -- Collect Common Ruby idioms.
https://github.com/fastruby/fast-ruby
5.67k stars 376 forks source link

Add test for `ARRAY.inject(:+)` vs `ARRAY.sum` #140

Open jrmhaig opened 6 years ago

jrmhaig commented 6 years ago

I was curious to see the difference between the sum method in enumerables, which was introduced in Ruby 2.4, and the commonly used inject(:+). For me inject(:+) is a little bit slower (1.02x).

This PR cannot be merged immediately as it will break for Ruby < 2.4. Do you have a way to only run tests for supported versions of Ruby?

jrmhaig commented 6 years ago

I am surprised to see that this passed in Travis CI even though, in the log with Ruby 2.3.0, there are errors:

$ ruby -v code/enumerable/inject-symbol-plus-vs-sum.rb
ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]
Warming up --------------------------------------
                 sumcode/enumerable/inject-symbol-plus-vs-sum.rb:7:in `fast': undefined method `sum' for #<Array:0x000000023deee0> (NoMethodError)
    from code/enumerable/inject-symbol-plus-vs-sum.rb:15:in `block (2 levels) in <main>'
    from /home/travis/build/JuanitoFatas/fast-ruby/vendor/bundle/ruby/2.3.0/gems/benchmark-ips-2.7.2/lib/benchmark/ips/job/entry.rb:53:in `call_times'
    from /home/travis/build/JuanitoFatas/fast-ruby/vendor/bundle/ruby/2.3.0/gems/benchmark-ips-2.7.2/lib/benchmark/ips/job.rb:220:in `block in run_warmup'
    from /home/travis/build/JuanitoFatas/fast-ruby/vendor/bundle/ruby/2.3.0/gems/benchmark-ips-2.7.2/lib/benchmark/ips/job.rb:206:in `each'
    from /home/travis/build/JuanitoFatas/fast-ruby/vendor/bundle/ruby/2.3.0/gems/benchmark-ips-2.7.2/lib/benchmark/ips/job.rb:206:in `run_warmup'
    from /home/travis/build/JuanitoFatas/fast-ruby/vendor/bundle/ruby/2.3.0/gems/benchmark-ips-2.7.2/lib/benchmark/ips/job.rb:185:in `block in run'
    from /home/travis/build/JuanitoFatas/fast-ruby/vendor/bundle/ruby/2.3.0/gems/benchmark-ips-2.7.2/lib/benchmark/ips/job.rb:184:in `times'
    from /home/travis/build/JuanitoFatas/fast-ruby/vendor/bundle/ruby/2.3.0/gems/benchmark-ips-2.7.2/lib/benchmark/ips/job.rb:184:in `run'
    from /home/travis/build/JuanitoFatas/fast-ruby/vendor/bundle/ruby/2.3.0/gems/benchmark-ips-2.7.2/lib/benchmark/ips.rb:59:in `ips'
    from code/enumerable/inject-symbol-plus-vs-sum.rb:14:in `<main>'

Is this intended?

I expected this error as ARRAY.sum will only work in 2.4.0+ but I also expected this to cause Travis to fail.

kbrock commented 6 years ago

maybe add a if RUBY > "2.4.0" ?

but I'm not a committer, so not sure the official way we do things here