Class: Hone::Patterns::CountVsSize
- Defined in:
- lib/hone/patterns/count_vs_size.rb
Overview
Pattern: array.count (no block) -> array.size or array.length
When count is called without a block on an Array, it's slower than
size/length because count is designed for enumerables and does more work.
.size and .length are O(1) operations for Arrays as they simply return
the cached length, while .count may iterate.
Instance Attribute Summary
Attributes inherited from Base
Instance Method Summary collapse
Methods inherited from Base
#add_finding, inherited, #initialize, scan_file
Constructor Details
This class inherits a constructor from Hone::Patterns::Base
Instance Method Details
#visit_call_node(node) ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/hone/patterns/count_vs_size.rb', line 15 def visit_call_node(node) super # Look for: receiver.count with no arguments and no block return unless node.name == :count && no_arguments?(node) && node.block.nil? add_finding( node, message: "Use `.size` or `.length` instead of `.count` when counting all elements", speedup: "Minor, but `.size` is O(1) for Arrays vs `.count` which may iterate" ) end |