我正在使用的代码如下:
Base.@kwdef struct cyl_struct
n::Int64
a::Array{Float64} = Array{Float64}(undef,n,2);
end
function adder(cyl)
for i in 1:cyl.n
cyl.a[i,1] = 1.0;
end
end
function adder2(a,n)
for i in 1:n
a[i,1] = 1.0;
end
end
n = 1000;
geom = cyl_struct(n=n);
@btime adder(geom)
@btime adder2(geom.a, geom.n)
运行此代码会给出输出:
23.700 μs (489 allocations: 7.64 KiB)
594.444 ns (3 allocations: 80 bytes)
我的问题是:当我将结构作为参数传递并在其中进行更改时,它会分配内存,但是当我将各个数组作为参数传递时,它不会分配内存。为什么?如何以在函数内部修改时不分配内存的方式传递结构对象?拜托,我需要你的帮助。预先感谢。
代码正在替换结构体的成员。您可以通过广播分配来引用成员的元素:
using BenchmarkTools
Base.@kwdef struct cyl_struct
n::Int64
a::Array{Float64} = Array{Float64}(undef, n, 2);
end
function adder(cyl)
for i in 1:n
cyl.a[i, 1] = 1.0
end
end
function adder1b(cyl)
cyl.a[1:cyl.n, 1] .= 1.0
end
function adder2(a, n)
for i in 1:n
a[i, 1] = 1.0
end
end
n = 1000
geom = cyl_struct(n = n);
@btime adder(geom)
@btime adder1b(geom)
@btime adder2(geom.a, geom.n)
产量
92.600 μs (1979 allocations: 46.56 KiB)
229.712 ns (2 allocations: 96 bytes)
686.755 ns (3 allocations: 80 bytes)