W0050 - Avoid using the size/1
BIF
Warning
-module(main).
-export([size/1]).
-type input() :: tuple() | binary().
-spec size(input()) -> non_neg_integer().
size(Input) ->
erlang:size(Input).
%% ^^^^^^^^^^^ 💡 warning: Avoid using the `size/1` BIF
Explanation
The size/1
BIF returns
the size for both tuples and binaries.
The BIF is not optimized by the JIT though, and its use can result in worse types for dialyzer and eqWAlizer.
When one knows that the value being tested must be a tuple, tuple_size/1
should always be preferred.
When one knows that the value being tested must be a binary, byte_size/1
should be preferred. However, byte_size/1
also accepts a bitstring (rounding
up size to a whole number of bytes), so one must make sure that the call to
byte_size/1
is preceded by a call to is_binary/1
to ensure that bitstrings
are rejected. Note that the compiler removes redundant calls to is_binary/1
,
so if one is not sure whether previous code had made sure that the argument is a
binary, it does not harm to add an is_binary/1
test immediately before the
call to byte_size/1
.
For the above use case, a better approach would be:
-module(main).
-export([size/1]).
-type input() :: tuple() | binary().
-spec size(input()) -> non_neg_integer().
size(Input) when is_tuple(Input) ->
erlang:tuple_size(Input);
size(Input) when is_binary(Input) ->
erlang:byte_size(Input).
For more information, see the Erlang common caveats.