Friday, March 22, 2013

more about what went wrong

So, let's share an example of memory-hogging code. This is the ClearArray routine that was sucking a lot of available memory out of Roodylib-using games:
routine ClearArray(array_to_be_cleared)
{
    local n,t
    for (n=0;n< array array_to_be_cleared[] ; n++ )
        {
            array array_to_be_cleared[n] = 0
        }
}

The problem was that I was using this with _temp_string every turn, and _temp_string has 256 elements, meaning that it goes through the loop 256 times. This all seems to count against the available memory.

The reason I wrote this routine in the first place was because of an instance in The Clockwork Boy 2 was because something was overwriting the end 0 bit of the current string, so the game kept printing until it got to the end of a previously-saved string. I thought, a-ha, I'll fix this by clearing _temp_string all of the time!

Of course, now I wish I had just fixed whatever was writing over that 0 bit. I can't remember what the code was like before, but in the meantime, I changed my PrintStatusLine code to not use ClearArray.

Instead of throwing ClearArray out altogether (although I might do it eventually anyway), I changed the loop to quit out as soon as the array has two empty elements in a row:

routine ClearArray(array_to_be_cleared)
{
    local n,t
    for (n=0;n< array array_to_be_cleared[] ; n++ )
        {
            if    array array_to_be_cleared[n] = 0
                t++
            else
            {
                array array_to_be_cleared[n] = 0
                t = 0
            }
            if t = 2
            {
                break
            }
        }
}

The main thing is, let this be a good lesson to not let your code loop more than it has to.

No comments:

Post a Comment