Skip to main content

W0064 - Use ets:lookup_element/4 instead of case ets:lookup/2

Warning

read(Tab, Key) ->
case ets:lookup(Tab, Key) of
%% ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 💡 W0064: Can be rewritten using `ets:lookup_element/4` for improved performance.
[{_, V}] -> V;
_ -> undefined
end.

Explanation

The warning indicates that you are using ets:lookup/2 in a case expression that immediately destructures the result to extract the second element of the tuple or return a default value. This pattern allocates an intermediate list and tuple that are immediately discarded.

Since OTP 26.2, ets:lookup_element/4 accepts a fourth argument as a default value to return when the key is not found, making this a direct replacement for the common case ets:lookup(...) pattern.

Why This Matters

  • Performance: ets:lookup_element/4 avoids allocating the intermediate [{Key, Value}] list and tuple
  • Readability: A single function call is clearer than a case expression with two clauses
  • Idiomatic Erlang: ets:lookup_element/4 is the idiomatic way to look up a value with a default since OTP 26.2

Patterns Detected

The diagnostic detects all of these equivalent forms:

%% Wildcard key, wildcard default
case ets:lookup(Tab, Key) of
[{_, V}] -> V;
_ -> Default
end

%% Wildcard key, empty list default
case ets:lookup(Tab, Key) of
[{_, V}] -> V;
[] -> Default
end

%% Empty list clause first
case ets:lookup(Tab, Key) of
[] -> Default;
[{_, V}] -> V
end

%% Key re-checked in tuple (redundant but common)
case ets:lookup(Tab, Key) of
[{Key, V}] -> V;
_ -> Default
end

Fix

Replace the case expression with a call to ets:lookup_element/4:

read(Tab, Key) ->
ets:lookup_element(Tab, Key, 2, undefined).

The third argument (2) refers to the position of the value in the ETS tuple (the first element is the key at position 1).

See Also