Class: RuboCop::Cop::Performance::InefficientHashSearch
- Inherits:
-
Base
- Object
- Base
- RuboCop::Cop::Performance::InefficientHashSearch
- Extended by:
- AutoCorrector
- Defined in:
- lib/rubocop/cop/performance/inefficient_hash_search.rb
Overview
Checks for inefficient searching of keys and values within hashes.
‘Hash#keys.include?` is less efficient than `Hash#key?` because the former allocates a new array and then performs an O(n) search through that array, while `Hash#key?` does not allocate any array and performs a faster O(1) search for the key.
‘Hash#values.include?` is less efficient than `Hash#value?`. While they both perform an O(n) search through all of the values, calling `values` allocates a new array while using `value?` does not.
Constant Summary collapse
- RESTRICT_ON_SEND =
%i[include?].freeze
Instance Method Summary collapse
- #on_send(node) ⇒ Object (also: #on_csend)
Instance Method Details
#on_send(node) ⇒ Object Also known as: on_csend
51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/rubocop/cop/performance/inefficient_hash_search.rb', line 51 def on_send(node) inefficient_include?(node) do |receiver| return if receiver.nil? = (node) add_offense(node, message: ) do |corrector| # Replace `keys.include?` or `values.include?` with the appropriate # `key?`/`value?` method. corrector.replace(node, replacement(node)) end end end |