5

I have functions which are called many times and require temporary arrays. Rather than array allocation happening every time the function is called, I would like the temporary to be statically allocated once.

How do I create a statically allocated array in Julia, with function scope?

3 Answers 3

5

Ok, let's assume that your function is called foo with an argument x and your array is just 100 hundred elements (each of which is a 64-bit value) with one dimension. Then you can create a scope around that function

let
    global foo
    let A = Array{Int64}(100)
    function foo(x)
        # do your tasks
    end
end

A should be a let variable since it would overwrite any other global A.

Sign up to request clarification or add additional context in comments.

Comments

2

You can wrap the temp array as a reference in a class:

type MyWrapper
    thetmparray
    thefunction::Function
    function MyWrapper(outertmp::Array)
        this = new(outertmp)
        this.thefunction = function()
            #use this.thetmparray or outertmp
        end
        return this
    end
end

This away you can avoid global variables and (in the future) have a per-executor/thread/process/machine/etc temp array.

Comments

1

You can use either the let block or partial application (I prefer this approach for such a case):

function bind_array(A::Array) 
    function f(x)
        A = A*x
    end
end

Now you can bind a private array to every new "instance" of your f:

julia> f_x = bind_array(ones(1,2))
f (generic function with 1 method)

julia> display(f_x(2))
1x2 Array{Float64,2}:
 2.0  2.0

julia> display(f_x(3))
1x2 Array{Float64,2}:
 6.0  6.0

julia> f_y = bind_array(ones(3,2))
f (generic function with 1 method)

julia> display(f_y(2))
3x2 Array{Float64,2}:
 2.0  2.0
 2.0  2.0
 2.0  2.0

julia> display(f_y(3))
3x2 Array{Float64,2}:
 6.0  6.0
 6.0  6.0
 6.0  6.0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.