Credence.Rule.AvoidGraphemesLength (credence v0.3.1)

Copy Markdown

Performance rule: Detects the use of length/1 on the result of String.graphemes/1.

Calling String.graphemes/1 eagerly allocates a list containing every grapheme in the string. If your only goal is to find out how many characters there are, this list is immediately garbage collected after length/1 finishes.

Using String.length/1 calculates the character count directly without building this intermediate list, making it significantly more memory efficient.

Bad

# In a pipeline
string
|> String.graphemes()
|> length()

# As a direct call
length(String.graphemes(string))

Good

String.length(string)

# Or in a pipeline:
string
|> String.length()