As you’ve already mentioned, Access‘s implementation was changed to use Behaviours instead of Protocols. The reasoning was performance.
- Protocols are type/data based polymorphism, and are exclusive to Elixir. That means it lets you dispatch based on the data structure
- Behaviours are a typeless mechanism that don’t rely on a data structure, but the module as an argument. They’re also built right into the Erlang/OTP ecosystem and are much more performant.
While Protocols do a lot of the heavy lifting for you when dispatching based on data types, they will still never be fast enough for Access because of the way they’re implemented (consolidation),
So although you should always use Protocols when you need to tie some functionality to a data structure rather than a Module, Access is a special case.
Because the
Accessprotocol relies on the code server in development and test mode (when protocol consolidation is not applied), we have heard multiple reports of the system suffering greatly in performance as the code server becomes a bottleneck with multiple processes.This happens because the
Accessprotocol ends up being invoked thousands of times and there isn’t much we can do to improve it (in contrast to the Enumerable protocol where most of the list cases are inlined).~ Jose Valim
Further Reading:
- Github: Get rid of the Access Protocol
- Elixir Forum: Why is Access a Behaviour instead of a Protocol
- Stackoverflow: Difference between Protocol & Behaviour in Elixir
- Mailing List: Understanding Protocols vs. Behaviours
- Blog post: Behaviours vs. Protocols