Ecto preload bandwith/memory efficiency?

Preface: I’m assuming that Post has a belongs_to relationship to Author

The preload: :author form is going to do a three-step process:

  • load the Post structs
  • collect all the author_ids from all the Posts
  • load those with one query like id IN (...) and fill in the author fields on all the Posts

So there’s one Author struct per distinct author in the results for this approach.

Each Post’s fields appear on the wire once, as do each Author’s.


In the explicit join case, things go differently:

  • the query returns all the post and author columns together.
  • Ecto builds Post structs from the results and caches Authors as they are seen (IIRC)

There’s also only one Author struct per distinct author for this approach. See this thread for an example where that wasn’t what the poster wanted

Each Posts fields appear on the wire once, but each Author’s fields appear once per Post they are the author of.


In general, prefer the preload: :author form unless there’s a specific reason (filtering, etc) to work harder.