To increase lookup performance we should add a way better storage rather than Map. That’s ETS — Erlang Term Storage — blazingly fast in-memory key-value storage.
Almost nothing have changed in API, the only difference is in whereis_name function. It doesn’t call gen_server callback any more, now client will perform all lookup queries. We just pass registry module and a key, and match key with a result. Very straightforward.
Also there is no new callbacks at all. We just use what we already have but with map replaced with ETS. Also there is no state in registry gen_server any more. All values are inside ETS table.
In init callback we initialize ETS table with parameters:
- :named_table — to identify table by it’s name;
- :protected — this is a default settings for the access rights. The owner process can read and write to the table, other processes only read;
- :set — the table is a set. One key, one object, no order among objects.
Register_name has only one change — it adds new row to the table with a key as a key and pid as a value.
Unregister_name removes matching row from the table.
DOWN handle_info callback do the same as unregister_name but using pid as a matching pattern because there is no information about the key.