Hello,
I don’t understand why any of the function calls underneath allocate memory on the heap.
My reasoning is that these are unmutable structs, so when the functions are called, the type of field ´a´ is known to be a Float64 and floats don’t need to be allocated on the heap.
Where am i wrong in my reasoning? And why does the only function call where ´@code_warntype´ wouldn’t know the type, allocate no memory?
using BenchmarkTools
struct untyped
a
end
struct typed{T}
a::T
end
function f(x)
x.a
end
function f2(x)
x.a::Float64
end
unt = untyped(5.0)
t = typed(5.0)
@btime f(unt) #18.837 ns (0 allocations: 0 bytes)
@btime f(t) #21.342 ns (1 allocation: 16 bytes)
@btime f2(unt) #22.067 ns (1 allocation: 16 bytes)
@btime f2(t) #21.406 ns (1 allocation: 16 bytes)
3 posts - 2 participants