In recent versions of Elixir, Access is no longer implemented as a protocol, but as a behaviour. From what I gather, this change was motivated by performance considerations in development mode.
Now, looking at the implementation, I wonder how this works internally and why this implementation was chosen. As we can see here, Access dispatches to a struct's module via the underlying map's "__struct__" key. AFAICS, this roughly works like OOP-style polymorphism. A few questions about this:
As you've already mentioned, Access
's implementation was changed to use Behaviours instead of Protocols. The reasoning was performance.
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
Access
protocol 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
Access
protocol 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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With