Does the fill pointer affect GC?
Asked Answered
P

1

5

If I have this struct:

(defstruct foo
  (x 0 :type 'fixnum))

and this array:

(defvar arr (make-array 0 :element-type 'foo :adjustable t :fill-pointer 0))

and then do the following:

(vector-push-extend (make-foo) arr)
(setf (fill-pointer arr) 0)

Is the foo in the array now a candidate for GC?

I understand from the CLHS that it is not active, but am unsure of the implications of that state.

Perkin answered 16/1, 2016 at 22:29 Comment(0)
S
10

Elements that are beyond the fill pointer are still accessible, and will not be garbage collected. Elements beyond the fill pointer aren't printed when you print the array, and they'll be overwritten if you use ARRAY-PUSH (since it uses the fill pointer to determine where to add the new element), but other operations on the array treat them normally.

For instance, the specification of AREF says:

aref ignores fill pointers. It is permissible to use aref to access any array element, whether active or not.

Sickle answered 16/1, 2016 at 22:57 Comment(10)
Thanks for this. Would it be possible to link to the place in the CLHS that explains this? I would love to read further.Perkin
I can't find any place that states it explicitly. It's implied by omission, since there's nothing that says that you can't access elements beyond the fill pointer.Sickle
This answer is exactly right. I learned this the hard way when using a huge array, assuming that the elements would be garbage collected. When I nulled out elements in addition to adjusting the full pointer, I got a huge performance increase and drastically lower memory usage.Laddie
@Perkin Found something in the AREF spec that says that inactive elements are still accessible.Sickle
@JoshuaTaylor I guess then the :element-type of the array would have to be (or boo null)?Perkin
@Perkin Not necessarily. You can either provide :initial-element to initialize the elements, or not access any elements you haven't assigned.Sickle
@Sickle that does make sense, but I was more referring to where Joshua says 'when I nulled out elements'. To null out the element means setting to nil right? Which I thought implies the type has to be (or boo null)Perkin
He might not have set the element type at all.Sickle
At the time, I think I was using an untyped array, so nil was fine, but in general you could just designate some known object to use. The point is to get rid of the references to the other contents.Laddie
Thanks to both of you, this is all much clearer now :)Perkin

© 2022 - 2024 — McMap. All rights reserved.