2

Is there a way in emacs-lisp to return cells to the free list once I do not use them any more? This would be useful in code where I build huge lists temporarily and can free them without waiting for garbage collector to do it.

This exists in other lisps but C-h a free did not return anything, and the Manual page about garbage collection does not mention anything like a free-cell function either.

phs
  • 1,095
  • 6
  • 13
  • AFAIK you just call `(garbage-collect)` after setting the head to nil. See the help about [garbage collection](https://www.gnu.org/software/emacs/manual/html_node/elisp/Garbage-Collection.html). – Tobias Jul 31 '18 at 11:53
  • I'm not sure I understand. I don't want to start a full garbage collection, I want to return specific cons cells to the free list. Is it what "after setting the head to nil" (??) would do? I am not sure what head you mean. – phs Jul 31 '18 at 12:39
  • 2
    AFAIK Full garbage collection is the only means in elisp to free memory. Assume you have a long list `my-list` and you want to free it. The right way to do it would be `(setq my-list nil) (garbage-collect)`. Could you give references about lisps that have something like `free-cell`. Cross-references into lists (e.g., `(setq my-2 (nthcdr 9 my-list))` make such functionality either difficult or dangerous. AFAIK only full garbage collection finds those cross references. – Tobias Jul 31 '18 at 14:36
  • I was thinking about a simple function that would do `(push cell free-list)` in a naive implementation. Yes it is dangerous, like using `free(ptr);` in C, but sometimes a programmer will use it in a safe situation where s/he knows that a series of cells are not referenced anymore and s/he just wants to delay garbage collection or extra memory usage. Sadly I don't know if some other lisp has it. I just checked the manual for CLISP and did not see it there :-/ – phs Jul 31 '18 at 15:14
  • 3
    I don't believe there's anything like that built-in, however, since conses are mutable, you could pool them. I.e. you could, basically, make your own allocator, where, while you wouldn't be able to instantly release the memory, you could mark it as unused and repurpose it for something else. – wvxvw Jul 31 '18 at 19:24
  • 2
    What's your use case? Sounds like you're trying to program in C++. ;-) Maybe this is an [XY problem](https://meta.stackexchange.com/q/66377/231821)? – Drew Jul 31 '18 at 19:43

0 Answers0