Skip to content

Commit

Permalink
Optimize list and map packing
Browse files Browse the repository at this point in the history
At least 10% and 20% respectively.
  • Loading branch information
lexmag committed Jul 22, 2019
1 parent a3d66ee commit 389058c
Showing 1 changed file with 14 additions and 8 deletions.
22 changes: 14 additions & 8 deletions lib/msgpax/packer.ex
Original file line number Diff line number Diff line change
Expand Up @@ -145,12 +145,15 @@ defimpl Msgpax.Packer, for: Map do
end

def pack(map) do
[format(map)] ++
for {key, value} <- map do
[@protocol.pack(key) | @protocol.pack(value)]
end
[format(map) | map |> Map.to_list() |> pack([])]
end

defp pack([{key, value} | rest], result) do
pack(rest, [@protocol.pack(key), @protocol.pack(value) | result])
end

defp pack([], result), do: result

defp format(map) do
length = map_size(map)

Expand All @@ -165,12 +168,15 @@ end

defimpl Msgpax.Packer, for: List do
def pack(list) do
[format(list)] ++
for item <- list do
@protocol.pack(item)
end
[format(list) | list |> Enum.reverse() |> pack([])]
end

defp pack([item | rest], result) do
pack(rest, [@protocol.pack(item) | result])
end

defp pack([], result), do: result

defp format(list) do
length = length(list)

Expand Down

0 comments on commit 389058c

Please sign in to comment.