Optimizing repeated atom creation in the C interface

Using the C interface, I create a mixed list that has a few repeated values (in this case nulls). This works fine:

knk(7,ks((S)sym),kf(nf),kf(nf),kf(nf),ki(ni),ki(ni),ki(ni))

I do this many times per second, and I’d prefer to create the atoms that repeat all the time only once, instead of fresh each time. (In the real code, there are non-nulls sometimes, but I wanted to keep the example simple.) We could do something like this:

K nullf = kf(nf);

K nulli = ki(ni);

knk(7,ks((S)sym),nullf, nullf, nullf, nulli, nulli, nulli)

I  know that I need to add calls to r1. The question is: do I need call r1 where I create the values with kf and ki, or at each use of the values inside the call to knk?

Thanks in advance

Fermín

each use

In hindsight, that’s the only possible answer if you know how garbage collection by reference counting works. When you decrement the reference count of an object, you also decrement the count of anything referenced by it. In my example below with a mixed list, the list references each of the items inside the list. Therefore, if you insert the same item into multiple lists (or into multiple places in the same list), each time you insert it the ref count of the item has to be increased by one.