I was experimenting with StaticArrays.jl
, and noticed the following issue with memory allocations. Consider the following example code:
using Random
using StaticArrays
function f1(X, h, D)
Y = D.*X- h;
return Y
end
function f2(X)
D = @SVector [0.1,1,1];
h = @SVector [0.1,0,0];
Y = D.*X- h;
return Y
end
function apply_n_times(X, f_func, n)
Y = copy(X)
for j = 1:n
Y = f_func(Y);
end
return Y
end
Random.seed!(100);
X = @SVector randn(3);
D = @SVector [0.1,1,1];
h = @SVector [0.1,0,0];
n = 10^4;
@time Y = apply_n_times(X, X->f1(X,h,D), n);
println(Y)
@time Y = apply_n_times(X, f2, n);
println(Y)
If I then run this a second time (after things get precompiled), I see the following results:
julia> @time Y = apply_n_times(X, X->f1(X,h,D), n);
0.017026 seconds (37.15 k allocations: 1.533 MiB)
julia> @time Y = apply_n_times(X, f2, n);
0.000051 seconds (5 allocations: 192 bytes)
Showing a substantial improvement in performance when I do not use the anonymous function. This leads to the following questions:
- Is this an inherent issue when using anonymous functions, or is it some combination of using them with
StaticArrays.jl
? - Is there a way to avoid this performance hit with anonymous functions?