Credence.Rule.NoEnumAtBinarySearch (credence v0.2.0)

Copy Markdown

Performance rule: Flags potential binary search patterns using Enum.at/2.

Elixir lists are linked lists. Enum.at/2 is an O(n) operation. Using it inside a binary search (which usually expects O(1) access) results in O(n log n) complexity, defeating the purpose of the algorithm.

If random access is required, convert the list to a tuple first using List.to_tuple/1 and use elem/2.

Bad

mid = low + div(high - low, 2)
mid_val = Enum.at(list, mid) # O(n) traversal inside a loop

Good

tuple = List.to_tuple(list)
# ... inside loop:
mid_val = elem(tuple, mid) # O(1) access