Tail-Call Optimization

Learn to create recursive functions that have constant and low memory consumption.

We'll cover the following

Introduction

Every time we call a function, it consumes memory. Usually, we don’t need to worry much about it, machines today have plenty of memory, and the Erlang VM does a great job keeping computation costs low for a decent amount of data. But when some input makes our function do millions of recursive calls – that consumes significant memory. In this section, we’ll discuss a way of creating recursive functions that have constant and low memory consumption. We’ll take advantage of compiler tail-call optimization.

Tail-call optimization is when the compiler reduces functions in memory without allocating more memory. It’s a common compiler feature in functional programming languages. To use it, we need to ensure that the last expression of our function is a function call. If the last expression is a new function call, then the current function’s return is the return of the new function call, and it doesn’t need to keep the current function in memory. Consider this example:

iex> scream = fn word -> String.upcase("#{word}!!!") end 
iex> scream.("help")
#Output -> "HELP!!!!"

Try it below:

Get hands-on with 1200+ tech skills courses.