@benchmark resize! : no memory allocation?

julia> using BenchmarkTools

julia> x = zeros(10);

julia> @benchmark resize!($x, 10000)
  memory estimate:  0 bytes
  allocs estimate:  0
  minimum time:     2.499 ns (0.00% GC)
  median time:      2.601 ns (0.00% GC)
  mean time:        2.720 ns (0.00% GC)
  maximum time:     23.999 ns (0.00% GC)
  samples:          10000
  evals/sample:     1000

julia> length(x)

In the above example, the size of x has been increased from 10 to 10000. However, @benchmark reports no memory allocation. Any explanation?

I don’t think you can increase size with resize! only decrease. I would have expected an error, though.

We can increase the size. Check the help:

  resize!(a::Vector, n::Integer) -> Vector

  Resize a to contain n elements. If n is smaller than the current collection length, the first n elements
  will be retained. If n is larger, the new elements are not guaranteed to be initialized.

BenchmarkTools.jl runs the function multiple times to give statistical results, in this case 10,000 samples. Only the first sample actually resized the array.

1 Like

You’re calling resize! on the same value over and over, so it has no effect at all after the very first iteration. Thus the number of allocations per iteration (after the first) is exactly zero.

The BenchmarkTools manual explains how to avoid this situation here: BenchmarkTools.jl/manual.md at master · JuliaCI/BenchmarkTools.jl · GitHub


julia> @btime resize!(x, 10000) setup=(x = zeros(10)) evals=1
  254.000 ns (1 allocation: 78.19 KiB)
1 Like

Thanks. You are correct. I want to verify the following hypothesis:

julia> @btime resize!(x, 10000) setup=(x=zeros(10000); resize!(x, 100)) evals=1;
  0.001 ns (0 allocations: 0 bytes)

After the first resize!(x, 100) inside setup, the memory originally allocated by x=zeros(10000) is not freed actually, right? I want to figure out whether Julia has the same behaviour as C++ std::vector in this case.