# Memory allocation in macro programming

**URL:** <https://discourse.julialang.org/t/memory-allocation-in-macro-programming/11706>\
**Category:** General Usage\
**Created:** [June 15, 2018, 5:44pm UTC](https://discourse.julialang.org/t/memory-allocation-in-macro-programming/11706 "2018-06-15T17:44:36Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![bkang119](https://avatars.discourse-cdn.com/v4/letter/b/a3d4f5/32.png) [@bkang119](https://discourse.julialang.org/u/bkang119)\
**Post date:** [June 15, 2018, 5:44pm UTC](https://discourse.julialang.org/t/memory-allocation-in-macro-programming/11706/1 "2018-06-15T17:44:36Z")

</div>

Hi I have a simple question regarding memory allocation in macro programming.

A simplified version of my question is as follows:  
Given an expression such as `ex1 = :(A[a,b,c])`, I would like to extract indices `:a`, `:b`, and `:c` out of it.  
I come up with a simple macro

```julia
macro getindices(ex)
    quote
        len = length( $(esc(ex)).args )
        indices = $(esc(ex)).args
        indices[2:len]
    end
end

```

which gives the desired output: `@getindices ex1` gives

```julia
3-element Array{Any,1}:
 :a
 :b
 :c

```

But then, there seems to exist memory allocation. Using the following test function:

```julia
function test(ex)
    for i=1:1000
        @getindices ex
    end
end

```

`@time test(ex1)` gives

```julia
  0.000262 seconds (1.00 k allocations: 109.531 KiB)

```

Is there any way to avoid the memory allocation?

---

<div class="post-metadata">

**Author:** ![pfitzseb](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/pfitzseb/32/45566_2.png) [@pfitzseb](https://discourse.julialang.org/u/pfitzseb)\
**Post date:** [June 15, 2018, 5:47pm UTC](https://discourse.julialang.org/t/memory-allocation-in-macro-programming/11706/2 "2018-06-15T17:47:32Z")

</div>

> [@bkang119](#):
>
> `indices[2:len]`

That’ll allocate a new array, so use something like `@view indices[2:len]` instead:

```julia
julia> @time test(ex1)
  0.000013 seconds (4 allocations: 160 bytes)

```

---

<div class="post-metadata">

**Author:** ![bkang119](https://avatars.discourse-cdn.com/v4/letter/b/a3d4f5/32.png) [@bkang119](https://discourse.julialang.org/u/bkang119)\
**Post date:** [June 15, 2018, 8:34pm UTC](https://discourse.julialang.org/t/memory-allocation-in-macro-programming/11706/3 "2018-06-15T20:34:09Z")

</div>

This works!! Thanks a lot 🙂
