Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Performance/InefficientHashSearch-20230602233137 #884

Merged
merged 3 commits into from
Jun 3, 2023

Conversation

github-actions[bot]
Copy link
Contributor

@github-actions github-actions bot commented Jun 2, 2023

Rubocop challenge!

Performance/InefficientHashSearch

Safe autocorrect: No
⚠️ The autocorrect a cop can yield false positives by design.

Description

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)

Auto generated by rubocop_challenger

@mathieujobin mathieujobin reopened this Jun 2, 2023
@mathieujobin mathieujobin merged commit 6a0227c into master Jun 3, 2023
@mathieujobin mathieujobin deleted the rubocop-challenge/20230602233137 branch June 3, 2023 00:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant