Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static array in Julia?

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?

like image 828
user2664470 Avatar asked Oct 08 '15 14:10

user2664470


3 Answers

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.

like image 99
Szymon Roziewski Avatar answered Sep 21 '22 14:09

Szymon Roziewski


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.

like image 45
Felipe Lema Avatar answered Sep 20 '22 14:09

Felipe Lema


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
like image 44
Maciek Leks Avatar answered Sep 22 '22 14:09

Maciek Leks