Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Lua use a garbage collector instead of reference counting?

I've heard and experienced it myself: Lua's garbage collector can cause serious FPS drops in games as their scripted part grows.

This is as I found out related to the garbage collector, where for example every Vector() userdata object created temporarily lies around until getting garbage collected.

I know that Python uses reference counting, and that is why it doesn't need any huge, performance eating steps like Luas GC has to do.

  • Why doesn't Lua use reference counting to get rid of garbage?
like image 477
Garbage man Avatar asked Feb 15 '11 22:02

Garbage man


2 Answers

Because reference counting garbage collectors can easily leak objects.

Trivial example: a doubly-linked list. Each node has a pointer to the next node - and is itself pointed to by the next one. If you just un-reference the list itself and expect it to be collected, you just leaked the entire list - none of the nodes have a reference count of zero, and hence they'll all keep each other alive. With a reference counting garbage collector, any time you have a cyclic object, you basically need to treat that as an unmanaged object and explicitly dispose of it yourself when you're finished.

Note that Python uses a proper garbage collector in addition to reference counting.

like image 190
Anon. Avatar answered Sep 23 '22 14:09

Anon.


While others have explained why you need a garbage collector, keep in mind that you can configure the garbage collection cycles in Lua to either be smaller, less frequent, or on demand. If you have a lot of memory allocated and are busy drawing frames, then make the thresholds very large to avoid a collection cycle until there is a break in the game.

Lua 5.1 Manual on garbage collection

like image 20
BMitch Avatar answered Sep 23 '22 14:09

BMitch