Class: RuboCop::Cop::Performance::InefficientHashSearch

Inherits:
Base
  • Object
show all
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.

Examples:

# bad
{ a: 1, b: 2 }.keys.include?(:a)
{ a: 1, b: 2 }.keys.include?(:z)
h = { a: 1, b: 2 }; h.keys.include?(100)

# good
{ a: 1, b: 2 }.key?(:a)
{ a: 1, b: 2 }.has_key?(:z)
h = { a: 1, b: 2 }; h.key?(100)

# bad
{ a: 1, b: 2 }.values.include?(2)
{ a: 1, b: 2 }.values.include?('garbage')
h = { a: 1, b: 2 }; h.values.include?(nil)

# good
{ a: 1, b: 2 }.value?(2)
{ a: 1, b: 2 }.has_value?('garbage')
h = { a: 1, b: 2 }; h.value?(nil)

Constant Summary collapse

RESTRICT_ON_SEND =
%i[include?].freeze

Instance Method Summary collapse

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?

    message = message(node)
    add_offense(node, message: message) do |corrector|
      # Replace `keys.include?` or `values.include?` with the appropriate
      # `key?`/`value?` method.
      corrector.replace(node, replacement(node))
    end
  end
end