Garbage Collection

From GPWiki

Files:GUITutorial_warn.gif The Game Programming Wiki has moved! Files:GUITutorial_warn.gif

The wiki is now hosted by GameDev.NET at wiki.gamedev.net. All gpwiki.org content has been moved to the new server.

However, the GPWiki forums are still active! Come say hello.

Garbage Collector is a code that manage the "garbage", that is the memory allocated and not used. Let's make an example, in C (actually it's used only to understand how the allocation is done)

/* 1 Create a pointer for some data */
int *pointer;
/* 2 Allocate 1000 bytes of data */
pointer = malloc(1000);
/* 3 Do something with the data, let's find the square root of the square root of 16... */
*pointer = 1 + 1;
/* 4 Now free the data */
free(pointer);

As you can see, this is a correct way to use memory

  • allocation (malloc)
  • use
  • deallocation (free)

Anyway, let say that in passage 3 you replace the pointer value

pointer = 0x123456;

This change the pointer value, which was pointing to the allocated memory. Since the memory is still allocated, but you can't get access to it - since no pointer are pointing to that memory - these cells are wasted, and become garbage.

Garbage is also memory used correcly and not free()ed: after using memory the program still have it allocated, and still aviable for use, but if you don't need that memory, and you don't free it, that memory is wasted, and become garbage.

Garbage collector is a piece of software - usually implemented as a thread in higher lever languages like Java or Python - that manage the memory to avoid wasting: when the memory is not accessible or not used, the garbage collector free it, making memory aviable for later use.

Some people love it, since memory is usually not wasted: memory leaks are often avoided using a garbage collector (and without it, the code usually produces memory leaks). Some other people don't like garbage collectors and prefer to continue the manual procedure of allocating and deallocating, actually the causes are that some garbage collectors sometimes fail to free, producing memory leaks or producing undesired anticipated deallocations.

Performance of garbage collectors usually aren't a problem, but keep in mind that

  • Garbage collector is an overhead in the memory management, because it must keep track of all the allocations, and keep track of the usage of the variables
  • Garbage collector do deallocations automatically when needed.

This second point isn't so great when you need performances: usually the deallocation is a relatively slow operation, so good programmers prefer to keep the deallocation for moments in which the game don't require much computational resources, or avoiding to free memory until it's necessary. But some garbage collectors may give you interfaces to control their usage, and let you to implement a such technique.

Links