Why does Julia allocate memory when I already pre-allocated?

Look at the code here.

julia> results = Vector{Int}(undef, 10^7);

julia> @time for i in 1:10^7
           results[i] = i
       end
  0.315568 seconds (20.00 M allocations: 305.160 MiB, 5.86% gc time)

Why is there memory allocation and GC run, when the vector was allocated beforehand?

results is global variable.

Do you mean that when an array is declared in global scope, I actually get an array of pointers to heap-allocated objects?

More likely there’s a bit of boxing and unboxing going on in each iteration of the loop while executing an unspecialized setindex!.

If you place the loop in a function with results as an argument or make results a const global you get more efficient code.

2 Likes

Thanks for the tips. I fixed the problem. I just had to add const before declaring the array results, and the memory allocation disappeared. I was aware that non-const globals are bad, but didn’t realize it would affect code as simple as this.

The simplicity of code matters not. If variable is global it allocates, so you should either use const or wrap in let block or wrap in a function. You can read more here: Performance Tips · The Julia Language

1 Like