Performance

Most slowness in Erlang comes from a handful of shapes, and all of them are visible in the code before a profiler runs: a list built by appending at the end, a term a message copies, output assembled as one big binary. Measure first, change one thing, measure again; the profiling lesson has the tools that say where the time goes, and this one has the three shapes worth fixing before them.

Build a list once

Prepending to a list is one cell and costs the same whatever the list length; ++ walks the whole left list, so growing a list with Acc ++ [X] in a loop is quadratic. The accumulator plus one reverse at the end is linear. The program builds twenty thousand elements both ways and compares the results rather than printing a time, which differs on every machine:

build.erl

-module(build). -export([main/0]). main() -> N = 20000, {AppendTime, Appended} = timer:tc(fun() -> append(N, []) end), {ConsTime, Consed} = timer:tc(fun() -> lists:reverse(cons(N, [])) end), io:format("same list: ~p~n", [Appended =:= Consed]), io:format("append is slower: ~p~n", [AppendTime > ConsTime]), io:format("both are timed: ~p~n", [AppendTime >= 0 andalso ConsTime >= 0]). append(0, Acc) -> Acc; append(N, Acc) -> append(N - 1, Acc ++ [N]). cons(0, Acc) -> Acc; cons(N, Acc) -> cons(N - 1, [N | Acc]).

erlc build.erl

erl -noshell -eval 'build:main(), halt().'

same list: true append is slower: true both are timed: true

timer:tc/1 answers {Microseconds, Value}, so a measurement and its result come back together. The page prints a comparison and not the microseconds, because the same run on another machine prints other numbers; the shape of the result, which is what matters here, is stable. The recursion lesson explains why the accumulator version is also the tail recursive one.

What a term costs

A list cell is two words, one for the head and one for the tail pointer, and a small integer fits in a word. erts_debug:size/1 counts a shared term once and erts_debug:flat_size/1 counts it at every reference, which is the difference between what a term costs and what a copy of it would cost:

size.erl

-module(size). -export([main/0]). main() -> List = lists:seq(1, 3), io:format("one list: ~p~n", [erts_debug:size(List)]), io:format("shared twice: ~p~n", [erts_debug:size([List, List])]), io:format("flat twice: ~p~n", [erts_debug:flat_size([List, List])]), Binary = binary:copy(<<"x">>, 1000), io:format("copied binary: ~p~n", [byte_size(Binary)]).

erlc size.erl

erl -noshell -eval 'size:main(), halt().'

one list: 6 shared twice: 10 flat twice: 16 copied binary: 1000

The pair [List, List] costs two cells plus the shared list once, so ten words, while flat_size charges the list twice and answers sixteen. The list has to be built at run time for the count to show the sharing: a literal [1, 2, 3] written twice is two literals in the module, and the size counts both. Erlang never copies a term it does not have to copy, which is why passing a big data structure to a process on the same node is cheap.

Build output as an iolist

A binary is copied every time it is joined with ++ or <>; a deep list of binaries and strings is not. iolist_to_binary/1 flattens it once, and io:format and gen_tcp:send/2 accept the deep list directly and flatten it on the way out:

iolist.erl

-module(iolist). -export([main/0]). main() -> Parts = [integer_to_list(N) || N <- lists:seq(1, 5)], IoList = [[Part, ","] || Part <- Parts], Binary = iolist_to_binary(IoList), io:format("bytes: ~p~n", [byte_size(Binary)]), io:format("text: ~s~n", [Binary]).

erlc iolist.erl

erl -noshell -eval 'iolist:main(), halt().'

bytes: 10 text: 1,2,3,4,5,

The deep list holds five small lists and five strings and no copy of the growing result, while the binary is built in one pass at the end. The output lesson and the strings lesson use the same idea for io:format and for a line of text. A join with lists:join/2 is the readable form of the same trick.

Runtime flags

The VM takes its own flags, and the default is right for most programs. +S sets the number of schedulers, +A the async thread pool for file and DNS work, +P the maximum number of processes and +Q the maximum number of ports. A node that does a lot of file IO benefits from a larger +A; a node with more processes than the default limit needs a larger +P. Change one flag at a time, and only after a measurement shows the limit.

The same numbers are readable at run time: erlang:system_info(process_count), erlang:system_info(run_queue) for the work waiting for a scheduler, and erlang:statistics(reductions) for the total work done. The observability lesson is the page that reads them from a running node.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Why is Acc ++ [X] in a loop slow?

    Answer

    It copies the left list on every step

    ++ walks its left argument, so the cost grows with the list on every step.

  2. What does the accumulator version pay at the end?

    Answer

    One reverse

    Prepending builds the list backwards, and one lists:reverse/1 restores the order in a linear pass.

  3. How many words does one list cell take on a 64-bit VM?

    Answer

    Two

    The head and the tail pointer are one word each.

  4. What does erts_debug:size/1 count for a shared term?

    Answer

    The term once

    size follows sharing, while flat_size charges the term at every reference.

  5. Why is an iolist cheaper than joining binaries with <>?

    Answer

    The pieces are flattened once at the end

    Building a deep list is cheap, and the writer or iolist_to_binary/1 flattens it in one pass.

  6. What does the +P flag of the VM set?

    Answer

    The maximum number of processes

    +P raises the process limit; +S, +A and +Q are the other three.

  7. What does this module print? -module(q1). -export([main/0]). main() -> N = 4, io:format("~p~n", [cons(N, [])]). cons(0, Acc) -> Acc; cons(N, Acc) -> cons(N - 1, [N | Acc]).

    Answer

    [1,2,3,4]

    The recursion prepends 4, then 3, 2 and 1 in front of it, so the list comes out in ascending order.

  8. What does this module print? -module(q2). -export([main/0]). main() -> List = lists:seq(1, 3), io:format("~p~n", [erts_debug:size([List, List])]).

    Answer

    10

    Two cells of the pair plus the shared list of three cells and three integers make ten words.

  9. What does this module print? -module(q3). -export([main/0]). main() -> Parts = [integer_to_list(N) || N <- lists:seq(1, 5)], Binary = iolist_to_binary([[Part, ","] || Part <- Parts]), io:format("~p~n", [byte_size(Binary)]).

    Answer

    10

    Five digits and five commas are ten bytes in the flattened binary.

  10. What does this module print? -module(q4). -export([main/0]). main() -> Binary = binary:copy(<<"ab">>, 3), io:format("~p~n", [byte_size(Binary)]).

    Answer

    6

    Three copies of the two byte binary make six bytes.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev