Improving Performance with NIFs
Explore how to improve the performance of genetic algorithms in Elixir using Native Implemented Functions (NIFs). Understand their benefits and risks, and learn to implement a basic random number generator in C to augment Elixir code. This lesson guides you through benchmarking, profiling, and deciding when to optimize or parallelize your algorithms to boost efficiency.
We'll cover the following...
What are NIFS?
Native Implemented Functions (NIFs) are a great way to inject speed into our Elixir/Erlang programs. NIFs are programs implemented in compiled languages like Rust or C/C++ that are then linked and loaded into our Elixir module at runtime.
NIFs were designed to be a simpler and more efficient way of interfacing with native code than ports. Ports interact with external programs and offer a mechanism for implementing program features in a different language.
NIFs are often used in places where Elixir/Erlang alone isn’t enough to efficiently get the job done. For example, the Matrex library uses NIFs to perform fast matrix operations because Elixir/Erlang isn’t optimized to perform these operations alone.
One thing to consider with NIFs is that they have the potential to crash the program. NIFs take the fault-tolerance out of applications because the code loaded is from an external program. Additionally, NIFs have a strange way of interacting with Erlang’s scheduler. The scheduler expects NIFs to return in a certain amount of ...