On Sun, Jan 3, 2016 at 12:20 PM, Stuart Brorson <[email protected]> wrote:
> Hello again Julia users,
>
> Sorry for the noise today, but I have another question which a quick
> search didn't answer.
>
> I am working on a function with a loop which creates an enlarged copy
> of the same matrix at every iteration.  Let's say it looks similar to
> this:
>
> for i = 1:N
>   A = zeros(BigFloat, 2^i, 2^i)
>   # Now do something with A...
> end
>
> I will guess that this is bad performance-wise since Julia needs to
> allocate a new array at each iteration through the loop.  Also, the GC
> needs to come along occasionally and clean up all my old, discarded
> arrays.  Meanwhile, I have accumulated a large number of old, unused
> copies of A.  Am I right about the performance problem?
>
> In C I would do something like this:
>
> for(i = 1; i<=N; i++) {
>   BigFloat* Ar = malloc((2i*2^i)*sizeof(BigFloat));
>   /* Please forgive the obvious problem with pointers here... */
>   /* Here I use the array */
>   free(Ar);
> }
>
> That would release the memory at the end of each iteration, and I
> could allocate a new Ar at the start of the next iteration.
>
> What's the right way to do this in Julia?  Is it OK to invoke a GC run
> at the end of each loop, or should I stop worrying and let Julia take
> care of memory allocation/deallocation?

Unless you are sure that you have an out-of-memory issue, don't call
GC yourself, it will be slower than letting the GC figuring out when
to do collection itself.

Also from your code, the array size grows exponentially so the memory
allocated in the previous loop is negligible compare to what you are
going to allocate.

>
> Thanks,
>
> Stuart

Reply via email to