Julia Function Barriers
A function barrier is a function that takes its data as an argument instead of reading it from outside. It lets Julia know the exact type of the data it works with.
Reading a list from outside allocates memory
sum_global reads the list from outside. It is warmed up, and the measured call still allocates bytes.
arr = [1, 2, 3, 4]
function sum_global()
total = 0
for x in arr
total += x
end
return total
end
sum_global()
println(@allocated sum_global())Passing the same list as an argument allocates nothing
sum_arg takes the list as an argument. It is warmed up, and the measured call allocates 0 bytes.
arr = [1, 2, 3, 4]
function sum_arg(a)
total = 0
for x in a
total += x
end
return total
end
sum_arg(arr)
println(@allocated sum_arg(arr))A barrier function passes its argument onward
total_for takes a list and passes it to sum_arg. It is warmed up, and the measured call allocates 0 bytes.
arr = [1, 2, 3, 4]
function sum_arg(a)
total = 0
for x in a
total += x
end
return total
end
function total_for(a)
return sum_arg(a)
end
total_for(arr)
println(@allocated total_for(arr))
println(total_for(arr))Example
scores = [10, 20, 30]
function add_all(a)
total = 0
for x in a
total += x
end
return total
end
function report(a)
return add_all(a)
end
report(scores)
println(report(scores))
println(@allocated report(scores))Key points
- Barrier: a function barrier is a boundary where data passes in as an argument.
- Outside data: a function that reads data from outside cannot always know its type.
- Argument data: data passed as an argument arrives with a known type.
- Use arguments to give a function the data it needs, instead of letting it reach outside.
- Small helpers: a small function that takes an argument can pass it to another function that also takes an argument.
In this example, report takes the list as an argument and passes it to add_all, and the printed total and count show the work and the 0-byte measurement.
Note
a global value can change type between calls, so Julia plans less firmly for it.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What is the main benefit of a function barrier?