Question: Memory allocation in function

Hi all,

I just want to check I have understood this right.

Example:

function Foo!(X)
X=X./2
return(X)
end

function TestFooAllocs()
A=[1 2 3];
@time A=Foo!(A);
end

Output:

0.000002 seconds (1 allocation: 112 bytes)
1×3 Array{Float64,2}:
0.5  1.0  1.5

In this example the single allocation is when I create A? I.e. when I manipulate this inside the function ‘foo’ is this assigned a new block of memory or not?

Hope my question makes sense.

X./2 creates a new array, which is then bound to X. You can modify the original array with X.=X./2.

1 Like

Nice, working REPL example below.

function Foo!(X)
X.=X./2
return(X)
end

function FooLoop!(X)
for i=1:length(X)
	X[i]= X[i]/2
end
return(X)
end

function TestFooAllocs()
A=[1. 2. 3.];
@time A=Foo!(A);
end

function TestFooLoopAllocs()
A=[1. 2. 3.];
@time A=FooLoop!(A);
end

TestFooAllocs()
TestFooLoopAllocs()

REPL outputs:

0.000000 seconds
1×3 Array{Float64,2}:
0.5  1.0  1.5

0.000000 seconds
1×3 Array{Float64,2}:
0.5  1.0  1.5

PS: also have a look at StaticArrays.jl. For small arrays those often work really well without requiring the gymnastics of in-place modifications.

2 Likes

It is not idiomatic to treat return as a function, since it is a keyword. You should rather write

return X

For benchmarking I recommend to use BenchmarkTools.jl, that way you also get more accurate memory numbers.

2 Likes