Writing Fast Elixir

Learn about the different optimization techniques and how lazy evaluation works.

Looking at optimization techniques

One of the first general rules for optimizing code states: “You can’t optimize a bad algorithm.” The most significant performance gains in our code will often come from better algorithms. Efficient algorithms can make up for limitations in computing power.

Note: A comprehensive introduction to data structure and algorithm design is outside of the scope of this course.

Instead, this lesson will cover some basic tips to increase the performance of the Elixir code. This is simply an overview and is not meant to be a comprehensive guide for writing fast Elixir.

Reduce or map?

A basic optimization we can make when we don’t need to preserve the order of our lists is to replace Enum.map/2 with Enum.reduce/3. The reason this works is that all of Elixir’s Enum functions are implemented using a reduce function. For example, in crossover, we could just as easily use Enum.map/2 to apply crossover to every pair of parents in the population, like this:

Get hands-on with 1200+ tech skills courses.