Big Bucket Software you like to use
In Soviet Russia, Garbage Collects You
November 3rd, 2006

For the last few months, as you are probably aware, I have been working on a J2ME game. It’s a sort of physics based puzzle game, nothing too fancy, but it’s fun. I will sell it one day and make millions. You’ll see. Anyway, a problem I was tackling recently involved doing some sorting. For anyone who hasn’t played with J2ME let me tell you, it’s not as simple as saying some_list_or_whatever.sort(). If you want to sort, you have to do it yourself, mate. So I slumped into my chair and pondered for a bit. After a bit of pondering, I figured that I would like to insert my items into the collection so that they are always sorted. To do this efficiently, I was going to need a linked list. Once again, J2ME ain’t gonna help me.

So I’m whipping up this Linked List basing my implementation on the one in J2SE and it’s all going quite well. For the heck of it, I decide to make it doubly linked to improve performance when traversing to a specific index, (why not, eh?). Anyway, back to story, I get to the clear method and without thinking I write:

    m_begin = null;
    m_end   = null;
    m_size  = 0;

Gee. Garbage collection in action. No need to traverse the list deleting each item. Sure that might just be common place to those of you brought up on Java, but I’ve been writing C++ since I graduated and memory management to me isn’t a bane, it’s just the way it is. I pictured this item chain anchored to earth by its to ends when suddenly someone calls clear. The chain is released and floats off into the sky until the garbage collector comes along and zaps it into nothing. Cute. Or even:

void trim(int first, int length)
{
    m_begin = find(first);
    m_end   = find(first + length);
    m_size  = length;
}

Everything out side those bounds just floats away. If for no other reason, I like garbage collected languages for the imagery.

Somehow I’ve always managed to avoid problems that involve tricky memory management. It just never come up. I would guess that non-trivial memory management problems only really occur when you need to build a (complex) data structure and when you’ve got a library like the STL at your disposal, that isn’t going to be often.