...

/

Strategy 1: Native Implemented Functions (NIFs)

Strategy 1: Native Implemented Functions (NIFs)

Learn and practice native implemented functions (NIFs) in this lesson.

What are NIFs?

Native implemented functions, or NIFs, allow developers to load external code into the same memory address space as the Erlang VM. Our code can integrate quite closely with functions implemented in other languages. While such tight integration may seem appealing because of the obvious performance benefits, we need to be careful. This power comes at a price. NIFs may be clean, but they do not necessarily share the same founding principles we do in ElixirLand. We must think of NIFs as unsafe. This is because of the following reasons:

  • A crash in a native function will crash the whole VM, not just one process.

  • A native function can cause internal VM inconsistencies, leading to crashes or unexpected behavior.

  • They may interfere with Elixir’s scheduling. A native function doing lengthy work can block other processes from running, causing inconsistent performance, high memory usage, and poor load balancing. We’ll learn more a little later.

n other words, NIFs are dangerous, and we should treat them as such.

Example

Let’s build a quick example of using NIFs within Elixir. The steps are straightforward. We’re going to create a project, build an Elixir module that loads a NIF, build our C NIFThe native implemented functions in C language., then build it all and run it. Let’s start a new project:

Press + to interact
mix new elixir_nif

We’ve already created one for you down below.

The main responsibility of the Elixir code is to define a template for functions that’ll be replaced when the C code is loaded by the VM. Let’s have a look at ...