Memory usage data for getproperty function

I’m analysing memory usage as described in julia manual , and I found that getproperty functions seem to be related to large numbers.
The following lines is taken from the result .mem file:

        - function Base.getproperty(system::System, v::Symbol)
1573581184     if v in [
        -             :lattice, :k_lattice, :Ω
        -         ]
        0         return getproperty(system.cell, v)
1797157632     elseif v in [
        -             :elements, :n_atoms, :n_species, :positions, :a2e_inds, :e2a_inds
        -         ]
        0         return getproperty(system.ions, v)

I think getproperty function should not need to allocate memories, so are these numbers only times the
corresponding lines are executed?

A little problem: the answer of @Gnimuc explains the reason and gives a solution, but I finally choose to adopt the tuple way as proposed by @Salmon . Whose answer should I mark as “Solution”?

Do not implement Base.getproperty in this way, use simple if-else instead:

if v === :lattice
  return getfield(system.cell, v)
elseif v === :k_lattice
   return getfield(system.cell, v)
...

I think getproperty function should not need to allocate memories, so are these numbers only times the
corresponding lines are executed?

Several arrays are created in your code, so the function allocates.

1 Like

I agree that this should get rid of the allocations. Do you know if it has any disadvantages to just use tuples instead of arrays? I.e

if v in (:lattice, :k_lattice, :Ω)
  return getproperty(system.cell, v)

I used similar style before without thinking much about it, so I’d be interested if this is something to stop in general

Tuple is generally OK, Julia compiler should be good at optimizing it.

1 Like