Do tries need to be destroyed?

I saw in documentation that tries will get atom garbage collected. I also saw that there is a trie_destroy. I was wondering when we’d want or need to call trie_destroy/1?

Indeed, atom garbage collection eventually will get rid of an unreferenced trie. Note the eventually though. AGC needs to be triggered, which by default happens if there are more than 10,000 atoms that could be subject to AGC. As yet, AGC has no idea and is not concerned with how much memory is involved in the handle. This can be huge in the case of tries. So, trie_destroy/1 cleans as much as possible, leaving the (atom) reference behind.

This mechanism is more or less common practice for blobs, atom-like references to “foreign” data. In particular if the resource is scarce (e.g., file handles for streams).

For short, if you know you are done with the trie and it could be big, call trie_destroy/1. Typically you embed this using setup_call_cleanup/3, where you create the trie in the setup, destroy it in the cleanup and use it in the main goal. If you deal with relatively small tries and/or it is hard to tell whether something may still be using the trie, leave them to AGC.

1 Like