Add new Performance/ArraySemiInfiniteRangeSlice cop#175
Conversation
spec/rubocop/cop/performance/array_semi_infinite_range_slice_spec.rb
Outdated
Show resolved
Hide resolved
spec/rubocop/cop/performance/array_semi_infinite_range_slice_spec.rb
Outdated
Show resolved
Hide resolved
844c097 to
d40868d
Compare
|
Thanks! |
|
|
|
This cop is not safe. Example: ".ext"[1..]
=> "ext"
".ext".drop(1)
NoMethodError (undefined method `drop' for ".ext":String) |
|
Didn't anyone file a bug report on MRI for this? The solution here is not to optimize Ruby code but MRI... |
|
Actually, this is just an error in the benchmarking. The creation of the range |
|
@marcandre I'm with you on this, a slight alteration of the example code gives the following results: Benchmarks# frozen_string_literal: true
require 'bundler/inline'
gemfile(true) do
gem 'benchmark-ips'
end
ARRAY = (1..100).to_a
range_take_3 = (..2).freeze
range_drop_90 = (90..).freeze
Benchmark.ips do |x|
x.report('Array#take(3)') { ARRAY.take(3) }
x.report('Array#[..2]') { ARRAY[..2] }
x.report('var Array#[..2]') { ARRAY[range_take_3] }
x.compare!
end
Benchmark.ips do |x|
x.report('Array#drop(90)') { ARRAY.drop(90) }
x.report('Array#[90..]') { ARRAY[90..] }
x.report('var Array#[90..]') { ARRAY[range_drop_90] }
x.compare!
endResultsHowever, Rubocop does not seem to detect the range usage when you're using variables... So as @marcandre said, the creation of a range is the factor that slows the benchmark down, not the usage of a Range to get a slice of an Array. Also, |
This cop was created due to a mistake in microbenchmark Refer rubocop#175 (comment) Closes rubocop#197, rubocop#198
This cop was created due to a mistake in microbenchmark Refer rubocop#175 (comment) Closes rubocop#197, rubocop#198
This cop was created due to a mistake in microbenchmark Refer rubocop#175 (comment) Closes rubocop#197, rubocop#198
This cop was created due to a mistake in microbenchmark Refer rubocop#175 (comment) Closes rubocop#197, rubocop#198
This cop was created due to a mistake in microbenchmark Refer rubocop#175 (comment) Closes rubocop#197, rubocop#198
This cop was created due to a mistake in microbenchmark Refer rubocop#175 (comment) Closes rubocop#197, rubocop#198
This cop was created due to a mistake in microbenchmark Refer rubocop/rubocop-performance#175 (comment) Closes #197, #198
This cop was created due to a mistake in microbenchmark Refer rubocop/rubocop-performance#175 (comment) Closes #197, #198
This cop was created due to a mistake in microbenchmark Refer rubocop/rubocop-performance#175 (comment) Closes #197, #198
This cop was created due to a mistake in microbenchmark Refer rubocop/rubocop-performance#175 (comment) Closes #197, #198
Inspired by fastruby/fast-ruby#181
Benchmarks
Results