More efficient algorithm to build a comment thread?

Im trying to find a way to efficiently build a comment thread tree for my app. I have a database table for the comments which the commented on resources ID as well as an optional comment_id which indicates a reply to an existing comment.

In order to rebuild this structure from a flat list of DB results I am doing this:

  defp build_comment_thread(comments) do
    lum = Enum.reduce(comments, %{}, &(Map.put(&2, &1.id, &1)))

    comments
    |> Enum.reduce(lum, fn
      (%{comment_id: nil} = comment, acc) -> acc
      (comment, acc) ->
        acc
        |> update_in([comment.comment_id, :comments], &([acc[comment.id] | &1]))
        |> Map.delete(comment.id)
    end)
  end

The list is sorted from the database in DESCending order. Now while this works I feel it could be improved. As a bit of a stress test I created a comment thread where of 1000 where all comments were replies to the previous comments. When I benchmarked this it took roughly 7ms which I feel can be greatly improved.

Honestly I just treat it like the DB in a form, I just put all comments in a flat map with their ID’s being the key’s, then they can access the next just by indexing back into the map.

2 Likes