Allocations and Memory Management#

Julia programmers tend to obsess about two things when they optimize code:

  • Runtime

  • Allocations (formally memory allocations)

Runtime refers to how much time it takes to run a program. Allocations refers to memory usage, and can have a dramatic effect on the runtime if you’re not careful. In general, the goal is to minimize the number of allocations your program has.

Quick Notes#

It’s a mess…

The notes below need to be cleaned up. For the time being, I’m putting them down at the speed of thought.

How to preallocate outputs:

Pass in the array as an argument (pass-by-sharing), and assign values to entries:1

function xinc!(ret::AbstractVector{T}, x::T) where T
    ret[1] = x
    ret[2] = x+1
    ret[3] = x+2
    nothing
end;

To make an in-place (non-allocating) assignment to a whole “slice” such as A[:,1], use the : notation on the left-hand side of an equals sign.2

function changeA(A,x)
    A[:,1] = x
    return nothing
end

Note

Usually A[:,1] creates a copy of the data in A[:,1]. However, the docs specifically state that A[:,1] = x makes an in-place assignment, and doesn’t make a copy.

How to avoid making copies

If you’re going to use a part of an array over and over, make a view.

xk = @view x[:,tt]

x[:,tt+1] = xk + timestep*f(xk,tt)

Fusing

Technical Details#

What exactly are allocations?#

Why do allocations affect performance?#

#