Hi guys, looking at the following two versions of codes. I found more allocations in version 2 perhaps because b is returned in version 2. However, b = [a] is also operated in both versions. Why is there a big difference in allocation?
BTW, b is stored in heap or stack and why? it seems b[1] === a so b[1] is a reference., but b is mutable structure and should be stored in the heap I guess.
Version 1
using BenchmarkTools
using StaticArrays
function m2()
a = SVector(1:32...)
b = [a]
a === b[1]
end
@btime m2() # 0 allocations
2.200 ns (0 allocations: 0 bytes)
true
Version 2
using BenchmarkTools
using StaticArrays
function m2()
a = SVector(1:32...)
b = [a]
#a === b[1]
end
@btime m2() # 0 allocations
Return doesn’t allocate, but it can prevent an allocation from being removed. Consider the following pair of examples
f1(n) = rand(n)
f2(n) = (rand(n); return nothing)
f1 obviously has to allocate a length n vector since that is what the function returns. f2 can be optimized to a simple return nothing because although, the function as written creates the same vector as f1, it provably doesn’t let anyone observe that the vector was created.