Julia 中的静态数组?

Static array in Julia?

我有一些函数被调用了很多次并且需要临时数组。而不是每次调用函数时都发生数组分配,我希望临时静态分配一次。

如何在 Julia 中创建具有函数作用域的静态分配数组?

好的,我们假设您的函数被调用为带有参数 x 的 foo,并且您的数组只有 10000 个一维元素(每个元素都是一个 64 位值)。然后你可以围绕该函数创建一个范围

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

A 应该是一个 let 变量,因为它会覆盖任何其他全局 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

这样你就可以 avoid global variables 并且(将来)有一个 per-executor/thread/process/machine/etc 临时数组。

您可以使用 let 块或部分应用程序(对于这种情况我更喜欢这种方法):

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

现在您可以将私有数组绑定到 f 的每个新 "instance":

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