Weird results while trying to measure allocation :/

Consider this Julia program:

f() = Vector{Int}(undef, 128*1024*1024)
(@timed f()).bytes
(r = @timed f()); r.bytes

Why do recent versions of Julia (v1.8 and up) evaluate the second line as 0? It really seems like the second and third line should be equivalent. This is the result for v1.11:

julia> f() = Vector{Int}(undef, 128*1024*1024)
f (generic function with 1 method)

julia> (@timed f()).bytes
0

julia> (r = @timed f()); r.bytes
1073741888

I guess Julia compiles the entire expression (@timed f()).bytes, figures out the allocations are unnecessary, and eliminates them?

Curiously it is related to the vector being intitalized with undef:

julia> f() = zeros(Int, 128*1024*1024)
f (generic function with 1 method)

julia> (@timed f()).bytes
1073741888

julia> (r = @timed f()); r.bytes
1073741888


3 Likes