On Mon, Sep 19, 2016 at 1:19 PM,  <vava...@uwaterloo.ca> wrote:
> Several of my functions start by allocating arrays used for intermediate
> computations in the function; these are then discarded at the end of the
> routine.  In other words, the structure of the function is like this:
>
>     function objective1(x)
>     ws1 = Array(Float64, length(x))
>     ws2 = Array(Int, 2*length(x))
>     # many computations involving x, ws1 and ws2
>     r  # r is the return value; no need for ws1 or ws2 any more
>     end
>
> For better efficiency, I would like to rewrite this code so that these work
> arrays are allocated once and for all by main using a larger preallocated
> object called "workspace".  For example, workspace would be a large array,
> and smaller arrays would be offsets into the large array.  It could be
> organized as a Dict whose keys are the data type, like this:
>
>     function objective1(x, workspace)
>     ws1 = WorkspaceArray(Float64, length(x), workspace[Float64])  #
> allocates the space for ws1 inside an array indexed by workspace[Float64]
>     ws2 = WorkspaceArray(Int, 2*length(x), workspace[Int])
>     #many computations here
>     r
>     end
>
> Is there a package or language feature that already does this?  I almost
> know how to write this myself.  The part I don't get is: how can "workspace"
> detect that "objective1" has finished so that it can reset its internal
> pointers?  I know that Julia has an "atexit" function to register functions
> to be called when Julia exits.  Is there also something like an "atreturn"
> function that registers functions to be called when a function returns?

No there's no callback for scope exit. You can pass the function body
as a closure to the allocation function which manages the lifetime
though. Similar to the `open(...) do` syntax/usage.

>
> Thanks,
> Steve Vavasis
>

Reply via email to