🎓 A1Learner
🔍
0 of 48 lessons completed

Julia Counting Allocations

Counting allocations is measuring how much new memory a call creates. It shows which calls create new memory and which create none.

A plain sum of numbers allocates nothing

add_pair is called once as a warm-up call. The measured call then allocates 0 bytes.

function add_pair(a, b)
    return a + b
end
add_pair(3, 4)
println(@allocated add_pair(3, 4))

Building a small list allocates memory

make_vec is called once as a warm-up call. The measured call builds a new list, so it allocates bytes.

function make_vec(n)
    return [i * 2 for i in 1:n]
end
make_vec(3)
println(@allocated make_vec(3))

Summing a ready list allocates nothing

The list is built before the measurement. sum_vec is warmed up, and the measured call allocates 0 bytes.

function sum_vec(a)
    total = 0
    for x in a
        total += x
    end
    return total
end
a = [1, 2, 3]
sum_vec(a)
println(@allocated sum_vec(a))

Example

function add_pair(a, b)
    return a + b
end
function make_vec(n)
    return [i * 2 for i in 1:n]
end
function sum_vec(a)
    total = 0
    for x in a
        total += x
    end
    return total
end
a = [1, 2, 3]
add_pair(3, 4)
make_vec(3)
sum_vec(a)
println(@allocated add_pair(3, 4))
println(@allocated make_vec(3))
println(@allocated sum_vec(a))

Key points

  • Allocation: an allocation is new memory created while a call runs.
  • Measure with @allocated: @allocated reports the number of bytes a call allocates.
  • Warm-up call: call a function once before measuring it, so compilation is not counted.
  • Zero result: a call that allocates 0 bytes creates no new memory.
  • List result: building a new list allocates memory for its items.

In this example, each function is warmed up once, and the three printed counts show a plain sum at 0, a new list at 80, and a sum over a ready list at 0.

Note

@allocated counts bytes, not time, so the same code gives the same count.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

Why must a function be called once before @allocated measures it?