Nested Loop optimization

copy and push! will both allocate, and usually you can avoid this by preallocating your memory. Work out how much memory you need first and create an array of that type. A crude example:

function  TXloop(a,b,c)
   # preallocate arrays at the start
   a_buffer = similar(a)
   m = zeros(eltype(a), Nt-1,length(a))
   for j = 2:Nt
      # same as copy, but doesn't allocate
      a_buffer .= a
      # calculate something

     # copy into a section of m
      m[j-1, :] .= a_buffer
    end
end

The .= operator is your friend when working with arrays as it broadcasts element-wise, and anything on the right hand side is fused to avoid allocating arrays for intermediate results. There’s also no reason you couldn’t also use a for loop.

Look for methods with a ! at the end of the name as these are mutating methods that alter the first argument, which usually let you do operations on some preallocated memory.

1 Like