# Why does indexing with a scalar allocate memory?

**URL:** https://discourse.julialang.org/t/why-does-indexing-with-a-scalar-allocate-memory/102656
**Category:** Performance
**Created:** [August 9, 2023, 11:03pm UTC](https://discourse.julialang.org/t/why-does-indexing-with-a-scalar-allocate-memory/102656 "2023-08-09T23:03:18Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![qua4tre](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/qua4tre/32/47504_2.png) [@qua4tre](https://discourse.julialang.org/u/qua4tre)
#### Post date: [August 9, 2023, 11:03pm UTC](https://discourse.julialang.org/t/why-does-indexing-with-a-scalar-allocate-memory/102656/1 "2023-08-09T23:03:18Z")

</div>

```julia
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?

---

<div class="post-metadata">

### Author: ![Benny](https://avatars.discourse-cdn.com/v4/letter/b/49beb7/32.png) [@Benny](https://discourse.julialang.org/u/Benny)
#### Post date: [August 9, 2023, 11:15pm UTC](https://discourse.julialang.org/t/why-does-indexing-with-a-scalar-allocate-memory/102656/2 "2023-08-09T23:15:00Z")

</div>

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
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

```

---

<div class="post-metadata">

### Author: ![algunion](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/algunion/32/51630_2.png) [@algunion](https://discourse.julialang.org/u/algunion)
#### Post date: [August 9, 2023, 11:44pm UTC](https://discourse.julialang.org/t/why-does-indexing-with-a-scalar-allocate-memory/102656/3 "2023-08-09T23:44:57Z")

</div>

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

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

```
