Reduce the allocations in the for loop

With the increase of Num, the allocations become larger and larger, can someone help me to optimize this program, here is an easy example
ps: in my program, Num is quite larger, ~100000

function test(x,y)
    c=rand(2).*[pi, 2pi]
    x+=c[1]
    y+=c[2]
    return x,y
end

Num=100
a=zeros(Num)
b=ones(Num)

@time begin

@inbounds for ii in 1:Num-1
    global a[ii+1],b[ii+1]=test(a[ii],b[ii])
end

end



To optimize:
First, wrap the thing in a function. Accessing a global variable is slowwwwwwww.
Second, set the an and b to undef and a[1] and b[1] to 0 and 1 respectively.
Finally, avoid using an array, you can use a pair of variables instead.

Read: Performance Tips · The Julia Language

And probably: Common allocation mistakes

1 Like

rand(2) will allocate a length=2 array, as will [pi,2pi], and then the product will allocate a third.

Consider using StaticArrays when you need small, fixed size arrays and you want them to be fast. With SVector, this could be non-allocating.

But in this specific case, it’s simple enough to avoid any array at all (although a SVector should be equally fast). For example, something like with test(x,y) = (x + rand()*pi, y + rand()*2pi).

Timing the loop in global scope will lead to many allocations. See the link to the performance tips from a previous post.

4 Likes