Memory allocation in macro programming


#1

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)
    quote
        len = length( $(esc(ex)).args )
        indices = $(esc(ex)).args
        indices[2:len]
    end
end

which gives the desired output: @getindices ex1 gives

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

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

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

@time test(ex1) gives

  0.000262 seconds (1.00 k allocations: 109.531 KiB)

Is there any way to avoid the memory allocation?


#2

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)


#3

This works!! Thanks a lot :slight_smile: