Memory allocation in macro programming

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

macro getindices(ex)
        len = length( $(esc(ex)).args )
        indices = $(esc(ex)).args

which gives the desired output: @getindices ex1 gives

3-element Array{Any,1}:

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

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

@time test(ex1) gives

  0.000262 seconds (1.00 k allocations: 109.531 KiB)

Is there any way to avoid the memory allocation?

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

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

1 Like

This works!! Thanks a lot :slight_smile: