How to create function barriers in Julia to improve performance?

Viewed 214

I was reading through some ideas about what a barrier in computer science is (specifically a function barrier) and wanted to know how this sort of thing can be replicated in my own Julia code. I have the following function:

julia> function strange_twos(n)
           a = Vector{rand(Bool) ? Int64 : Float64}(undef, n)
           for i = 1:n
               a[i] = 2
           end
           return a
       end;

How would I go about adding a barrier to this function to improve performance?

1 Answers

The way to break this down is as follows:

julia> function fill_twos!(a)
           for i = eachindex(a)
               a[i] = 2
           end
       end;

julia> function strange_twos(n)
           a = Vector{rand(Bool) ? Int64 : Float64}(undef, n)
           fill_twos!(a)
           return a
       end;

The reason this implementation is fast is because in the original loop, the type of a was not known during the loop itself. However in the example provided above, the type of a will be know when the function is called so the code can be pre-compiled which improves speed.

You can read more about this in the Julia docs under the Performance improvements section: https://docs.julialang.org/en/v1/manual/performance-tips/#kernel-functions

Related