Why does indexing with a scalar allocate memory?

julia> @time 2.0;
  0.000005 seconds

julia> x = fill(2.0, 3)
3-element Vector{Float64}:
 2.0
 2.0
 2.0

julia> @time x[1];
  0.000009 seconds (1 allocation: 16 bytes)

I would have assumed x[1] would be a nonallocating expression because it returns a scalar instead of an array like x[1:2]. Why does x[1] allocate memory?

It’s global scope stuff. The Performance Tips says that running @time in the global scope can cause small allocations sometimes, but in this case typing the global variable also gets to 0 allocations.

julia> x = fill(2.0, 3); x[1]; @time x[1]
  0.000005 seconds (1 allocation: 16 bytes)
2.0

julia> let
         x = fill(2.0, 3); x[1]; @time x[1]
       end
  0.000001 seconds
2.0

julia> typedx::Vector{Float64} = fill(2.0, 3); typedx[1]; @time typedx[1]
  0.000002 seconds
2.0
3 Likes

The other global-scope-related tip is about const usage - which also results in 0 allocations (particularly for this scenario).

const x = fill(2.0, 3)
@time x[1] # no allocations
2 Likes