Skip to content

Commit 4594904

Browse files
committed
perf: replace list length-checks with pattern matching
This replaces few length check on hot paths with patternmatching. According to benchmarks I ran it gives 3-8% or performance gains on parsing a realistic files.
1 parent c1a4f1b commit 4594904

1 file changed

Lines changed: 13 additions & 8 deletions

File tree

lib/spitfire.ex

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -965,16 +965,21 @@ defmodule Spitfire do
965965
end
966966

967967
defp invalid_assoc_key_in_map?({name, meta, args}) when is_atom(name) and is_list(meta) and is_list(args) do
968-
arity = length(args)
968+
case args do
969+
[_, _ | _] ->
970+
arity = length(args)
969971

970-
arity > 1 and
971-
not Macro.operator?(name, arity) and
972-
not Macro.special_form?(name, arity) and
973-
invalid_assoc_call_meta?(meta)
972+
not Macro.operator?(name, arity) and
973+
not Macro.special_form?(name, arity) and
974+
invalid_assoc_call_meta?(meta)
975+
976+
_ ->
977+
false
978+
end
974979
end
975980

976981
defp invalid_assoc_key_in_map?({{:., _, [_lhs, _rhs]}, meta, args}) when is_list(meta) and is_list(args) do
977-
length(args) > 1 and invalid_assoc_call_meta?(meta)
982+
match?([_, _ | _], args) and invalid_assoc_call_meta?(meta)
978983
end
979984

980985
defp invalid_assoc_key_in_map?({{name, meta, args}, _value}) when is_atom(name) and is_list(meta) and is_list(args) do
@@ -3175,7 +3180,7 @@ defmodule Spitfire do
31753180
{Enum.reverse(pairs), parser}
31763181
end
31773182

3178-
if length(pairs) == 2 do
3183+
if match?([_, _], pairs) do
31793184
tuple = encode_literal(parser, pairs |> List.wrap() |> List.to_tuple(), orig_meta)
31803185
parser = Map.put(parser, :nesting, old_nesting)
31813186
{tuple, parser}
@@ -3397,7 +3402,7 @@ defmodule Spitfire do
33973402

33983403
true ->
33993404
meta =
3400-
if identifier == :op_identifier && length(args) == 1 do
3405+
if identifier == :op_identifier && match?([_], args) do
34013406
[{:ambiguous_op, nil} | meta]
34023407
else
34033408
meta

0 commit comments

Comments
 (0)