Kristoffer,

I forgot to ask: did you actually benchmark the code and confirm that
the allocation of arrays is the bottleneck? Our of curiosity, I
benchmarked some code of mine that uses arrays with and without
allocation (reusing the same one, since dimensions match), and found the
difference to be negligible. YMMV of course, but it would be interesting
to see a nontrivial example where allocation is a significant main cost
--- allocating un-initialized arrays (with Array) should be fairly
cheap.

Best,

Tamas

On Fri, Feb 20 2015, Tamas Papp <tkp...@gmail.com> wrote:

> You could create an array pool:
>
> arraypool = Dict()
>
> function emptyarray(elttype, dimensions...)
>   get!(() -> Array(elttype, dimensions...), arraypool, (elttype,
> dimensions))
> end
>
> When you request the same kind of array, it will recycle a preallocated one:
>
> a = emptyarray(Float64, 1, 2, 3)
> is(a, emptyarray(Float64, 1, 2, 3)) # true
>
> That said, unless you have compelling reasons to avoid passing empty arrays
> as extra arguments, this is a great way to introduce subtle bugs if you are
> not careful --- if you keep using the array from the pool for something
> else, it can be silently overwritten next time you call your function. You
> may lose some type stability with the code above, I did not check. Also,
> unused arrays will not be GC'd, since the pool still refers to them.
>
> Best,
>
> Tamas
>
>
> On Friday, February 20, 2015 at 1:05:08 PM UTC+1, Kristoffer Carlsson wrote:
>>
>> I call a function repeatedly that creates a few arrays, does a computation
>> with these arrays and then return a result.
>>
>> Every time the function returns the arrrays are destroyed and new ones are
>> created at the next call. Very unnecessary, I could just as well overwrite
>> what was in the arrays and then not having to reallocate memory.
>>
>> I could of course preallocate these arrays and send them in as function
>> arguments, however this would propagate to many of my function taking extra
>> arguments.
>>
>> Is there a better way?
>>
>> Best regards,
>> Kristoffer Carlsson
>>

Reply via email to