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?
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
.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With