Memory Allocation on Array Element Operations

Hi,
I currently have the problem that i want to add elements from a Vector to other, more or less random, elements of a matrix. Because i have to do this a lot of times i wanted to improve the performance of it. And that’s when i realized that Julia does memory allocations when Elements of an Array are added. Like in the following example:

julia> a = ones(2);
julia> B  = ones(2, 2);
julia> @allocated B[1, 2] += a[2]
48

My question now is, how can this allocation be avoided? Is there a way to do it? And a second question just out of interest, what is the reason for the allocation in the first place?

because your variables are in global scope thus type instability forces Julia to perform boxing and unboxing:

julia> const a = ones(2);

julia> const B  = ones(2, 2);

julia> @allocated B[1, 2] += a[2]
0

this doesn’t happen as soon as you start doing real operations inside functions

2 Likes

There isn’t really an allocation there, that is coming only from the printing of the result to the REPL (or the global scope of the variables as pointed above, or both, I’m not completely sure):

julia> using BenchmarkTools

julia> a = ones(2);

julia> B  = ones(2, 2);

julia> @ballocated $B[1,2] += $a[2]
0

You can also verify that if you put that in a function that returns nothing:

julia> function up(a,B) 
         B[1,2] += a[2]
         nothing
       end
up (generic function with 1 method)

julia> @allocated up(a,B) # first run compiles
96518

julia> @allocated up(a,B)
0
2 Likes